funseek 0.1.1__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.
funseek/__init__.py ADDED
File without changes
funseek/cli.py ADDED
@@ -0,0 +1,680 @@
1
+ import time
2
+ import typer
3
+ from pathlib import Path
4
+ import hashlib, json
5
+ import os
6
+
7
+ from rich.console import Console
8
+ from rich.markup import escape
9
+
10
+ from funseek.parsing.parser import CodebaseParser
11
+ from funseek.retrieval.types import ScoredFunction
12
+ from funseek.pipeline.fusion import Fuser
13
+ from funseek.pipeline.reranker import Reranker
14
+ from funseek.providers.gemini import GeminiProvider
15
+ from funseek.providers.ollama import OllamaProvider
16
+
17
+
18
+ REGISTRY_PATH = Path.home() / ".funseek" / "registry.json"
19
+ BM25_DIR = Path.home() / ".funseek" / "bm25"
20
+ GRAPH_DIR = Path.home() / ".funseek" / "graphs"
21
+ CHROMA_DIR = Path.home() / ".funseek" / "chroma"
22
+
23
+ VALID_KEY_PROVIDERS = {"gemini"}
24
+
25
+ os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"
26
+ os.environ["HF_HUB_VERBOSITY"] = "error"
27
+
28
+ console = Console(highlight=False)
29
+ error_console = Console(stderr=True, highlight=False)
30
+
31
+ class CorruptedRegistryError(Exception):
32
+ """
33
+ Raised when the registry file is corrupted.
34
+ """
35
+ pass
36
+
37
+
38
+ def compute_project_hash(folder: Path) -> str:
39
+ return hashlib.sha256(folder.as_posix().encode("utf-8")).hexdigest()
40
+
41
+ def load_registry() -> dict:
42
+ if not REGISTRY_PATH.exists():
43
+ return {}
44
+ try:
45
+ registry = json.loads(REGISTRY_PATH.read_text(encoding="utf-8"))
46
+ except (json.JSONDecodeError, UnicodeDecodeError, OSError):
47
+ raise CorruptedRegistryError(f"Registry file {REGISTRY_PATH} is corrupted.")
48
+ if not isinstance(registry, dict):
49
+ raise CorruptedRegistryError(f"Registry file {REGISTRY_PATH} is corrupted.")
50
+ return registry
51
+
52
+ def safe_load_registry_index_cmds() -> dict:
53
+ try:
54
+ registry = load_registry()
55
+ return registry
56
+ except CorruptedRegistryError:
57
+ backup_date_time = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
58
+ backup = REGISTRY_PATH.with_name(f"registry.corrupted-{backup_date_time}.json")
59
+ try:
60
+ REGISTRY_PATH.rename(backup)
61
+ error_console.print(
62
+ f"[bold yellow]Warning: [/bold yellow]Registry was corrupted. Moved to {escape(backup.as_posix())}."
63
+ f" Starting fresh Registry"
64
+ )
65
+ console.print()
66
+ return {}
67
+ except OSError:
68
+ error_console.print(f"[bold yellow]Warning: [/bold yellow]Registry is corrupted and could not be backed up")
69
+ confirm = typer.confirm("Do you want to initialize new registry without backing up the corrupted one", default=False)
70
+ if not confirm:
71
+ raise typer.Exit(code=0)
72
+ return {}
73
+
74
+ def save_registry(registry: dict) -> None:
75
+ REGISTRY_PATH.parent.mkdir(parents=True, exist_ok=True)
76
+ REGISTRY_PATH.write_text(json.dumps(registry, indent=2), encoding="utf-8")
77
+
78
+ def get_file_mtimes(folder: Path, include_tests: bool) -> dict[str, float]:
79
+ skip_dirs = {
80
+ "__pycache__", ".git", "venv", ".venv", "node_modules", "dist", "build",
81
+ ".eggs", "egg-info", ".idea", ".vscode", ".pytest_cache", ".mypy_cache",
82
+ ".tox",
83
+ }
84
+
85
+ file_mtimes: dict[str, float] = {}
86
+
87
+ for dirpath, sub_dirnames, filenames in os.walk(folder):
88
+ sub_dirnames[:] = [
89
+ d for d in sub_dirnames
90
+ if (d not in skip_dirs and (include_tests or d not in {"tests", "test"}))
91
+ ]
92
+
93
+ for filename in filenames:
94
+ if filename.endswith(".py"):
95
+ if not include_tests and (filename.startswith("test_") or filename.endswith("_test.py")):
96
+ continue
97
+ filepath = Path(dirpath) / filename
98
+ file_mtimes[filepath.as_posix()] = filepath.stat().st_mtime
99
+
100
+ return file_mtimes
101
+
102
+ def get_indexes(folder: Path, no_index: bool, include_tests: bool, timings: bool) -> tuple["BM25Index", "VectorIndex", "GraphIndex", float, float, float]:
103
+ if not no_index:
104
+ project_hash = compute_project_hash(folder)
105
+
106
+ try:
107
+ registry = load_registry()
108
+ except CorruptedRegistryError:
109
+ error_console.print(
110
+ f"[b red]Error: [/b red]The registry is corrupted, so {escape(str(folder))} cannot be looked up. "
111
+ f"Run 'fun reindex {escape(str(folder))}' to fix it."
112
+ )
113
+ raise typer.Exit(code=1)
114
+
115
+ if project_hash not in registry:
116
+ error_console.print(f"[bold yellow]Warning: [/bold yellow]{escape(str(folder))} is not indexed. Run 'fun index {escape(str(folder))}' first.")
117
+ raise typer.Exit(code=1)
118
+
119
+ indexed_project = registry[project_hash]
120
+ include_tests = indexed_project["include_tests"]
121
+
122
+ current_mtimes = get_file_mtimes(folder, include_tests=include_tests)
123
+ if current_mtimes != indexed_project["file_mtimes"]:
124
+ error_console.print(f"[bold yellow]Warning: [/bold yellow]Files in {escape(str(folder))} have changed since last index.")
125
+ proceed = typer.confirm("Search anyway with the existing index?", default=True)
126
+ if not proceed:
127
+ console.print()
128
+ console.print(f"Run 'fun reindex {escape(str(folder))}' to update.")
129
+ raise typer.Exit(code=0)
130
+
131
+ try:
132
+ console.print()
133
+ with console.status("Fetching indexes...", spinner="arc"):
134
+ from funseek.indexing.bm25_index import BM25Index
135
+ from funseek.indexing.vector_index import VectorIndex
136
+ from funseek.indexing.graph_index import GraphIndex
137
+
138
+ tb0 = time.perf_counter()
139
+ bm25_index = BM25Index.load(BM25_DIR / f"{project_hash}.pkl")
140
+ tb1 = time.perf_counter()
141
+
142
+ tv0 = time.perf_counter()
143
+ vector_index = VectorIndex.load(
144
+ collection_name=project_hash,
145
+ persist_path=CHROMA_DIR,
146
+ model_name=indexed_project["vector_index_embedding_model"],
147
+ )
148
+ tv1 = time.perf_counter()
149
+
150
+ tg0 = time.perf_counter()
151
+ graph_index = GraphIndex.load(GRAPH_DIR / f"{project_hash}.pkl")
152
+ tg1 = time.perf_counter()
153
+
154
+ except Exception as e:
155
+ error_console.print(f"[b red]Error:[/b red] Failed to load indexes: {escape(str(e) or type(e).__name__)}. Run 'fun reindex <folder>' to rebuild.")
156
+ raise typer.Exit(code=1)
157
+
158
+
159
+ return bm25_index, vector_index, graph_index, tb1 - tb0, tv1 - tv0, tg1 - tg0
160
+
161
+ else:
162
+ parser = CodebaseParser(include_tests=include_tests)
163
+
164
+ with console.status("Parsing codebase...", spinner="arc"):
165
+ tp0 = time.perf_counter()
166
+ functions = parser.parse_dir(folder)
167
+ tp1 = time.perf_counter()
168
+
169
+ if parser.skipped_files:
170
+ error_console.print(
171
+ f"[bold yellow]Warning: [/bold yellow]Skipped [cyan]{len(parser.skipped_files)}[/cyan] file(s) "
172
+ f"that could not be parsed (for example syntax errors, unsupported encoding, unreadable files, or very deeply nested code). "
173
+ f"Functions in them will not be searchable."
174
+ )
175
+ console.print()
176
+
177
+ if not functions:
178
+ error_console.print(f"[bold yellow]Warning: [/bold yellow]No functions found in {escape(str(folder))}. Nothing to index.")
179
+ raise typer.Exit(code=1)
180
+
181
+ console.print(f"Parsed [cyan]{len(functions)}[/cyan] functions")
182
+ if timings:
183
+ console.print(f"[dim]Parsing took [cyan]{tp1 - tp0:.2f}[/cyan] seconds.[/dim]")
184
+
185
+
186
+ try:
187
+ console.print()
188
+ with console.status("Building indexes...", spinner="arc"):
189
+ from funseek.indexing.bm25_index import BM25Index
190
+ from funseek.indexing.vector_index import VectorIndex
191
+ from funseek.indexing.graph_index import GraphIndex
192
+
193
+ ttb0 = time.perf_counter()
194
+ bm25_index = BM25Index.build(functions)
195
+ ttb1 = time.perf_counter()
196
+
197
+ ttv0 = time.perf_counter()
198
+ vector_index = VectorIndex.build(functions, persist=False)
199
+ ttv1 = time.perf_counter()
200
+
201
+ ttg0 = time.perf_counter()
202
+ graph_index = GraphIndex.build(functions)
203
+ ttg1 = time.perf_counter()
204
+
205
+ except Exception as e:
206
+ error_console.print(f"[b red]Error:[/b red] Failed to build indexes: {escape(str(e) or type(e).__name__)}")
207
+ raise typer.Exit(code=1)
208
+
209
+
210
+ return bm25_index, vector_index, graph_index, ttb1 - ttb0, ttv1 - ttv0, ttg1 - ttg0
211
+
212
+
213
+ def search_helper(bm25_retriever: "BM25Retriever",
214
+ vector_retriever: "VectorRetriever",
215
+ graph_retriever: "GraphRetriever",
216
+ fuser: Fuser,
217
+ query: str,
218
+ max_hop: int,
219
+ decay_factor: float,
220
+ num_rerank_candids: int,
221
+ timings : bool = False) -> list[ScoredFunction]:
222
+ tbs0 = time.perf_counter()
223
+ bm25_results = bm25_retriever.search(query)
224
+ tbs1 = time.perf_counter()
225
+
226
+ tvs0 = 0.0
227
+ tvs1 = 0.0
228
+ try:
229
+ tvs0 = time.perf_counter()
230
+ vector_results = vector_retriever.search(query)
231
+ tvs1 = time.perf_counter()
232
+ except Exception as e:
233
+ error_console.print(f"[bold yellow]Warning: [/bold yellow]Vector search failed ({escape(str(e) or type(e).__name__)}), continuing with keyword + structural search only.")
234
+ vector_results = []
235
+
236
+ seeds = bm25_results[:10] + vector_results[:10]
237
+
238
+ tgs0 = time.perf_counter()
239
+ graph_results = graph_retriever.search(seeds, max_hop=max_hop, decay_factor=decay_factor)
240
+ tgs1 = time.perf_counter()
241
+
242
+ if timings:
243
+ console.print(f"[dim]BM25 search took [cyan]{tbs1 - tbs0:.2f}[/cyan] seconds.[/dim]")
244
+ if tvs1 != 0.0:
245
+ console.print(f"[dim]Vector search took [cyan]{tvs1 - tvs0:.2f}[/cyan] seconds.[/dim]")
246
+ console.print(f"[dim]Graph search took [cyan]{tgs1 - tgs0:.2f}[/cyan] seconds.[/dim]")
247
+ console.print()
248
+
249
+ fused_results = fuser.fuse(bm25_results, vector_results, graph_results[:10])
250
+ rerank_candidates = fused_results[:num_rerank_candids]
251
+
252
+ return rerank_candidates
253
+
254
+
255
+ def rerank_results(query: str, candidates: list[ScoredFunction], reranker: Reranker, skip_reason: str, top_n: int, timings: bool) -> list[ScoredFunction]:
256
+ if reranker is None:
257
+ error_console.print(f"[bold yellow]Warning: [/bold yellow]{skip_reason} Skipping reranking, showing fused results.")
258
+ console.print()
259
+ return candidates[:top_n]
260
+
261
+ tr0 = time.perf_counter()
262
+ with console.status("Reranking...", spinner="arc"):
263
+ final = reranker.rerank(query, candidates)
264
+ tr1 = time.perf_counter()
265
+
266
+ if timings and final[0].retriever == "reranked":
267
+ console.print(f"[dim]Reranking took [cyan]{tr1 - tr0:.2f}[/cyan] seconds.[/dim]")
268
+ return final
269
+
270
+
271
+ def print_results(query: str, final_results: list[ScoredFunction]) -> None:
272
+ console.print(f"Results for: \"{escape(str(query))}\"\n")
273
+ for i, result in enumerate(final_results, start=1):
274
+ func = result.function
275
+ console.print(f"[cyan]{i}[/cyan]. [b white]{func.name}[/b white] [bright_blue]{escape(func.file.as_posix())}:{func.line}[/bright_blue]")
276
+ if result.explanation:
277
+ console.print(f" {escape(str(result.explanation))}")
278
+ console.print()
279
+ console.print()
280
+
281
+
282
+ app = typer.Typer()
283
+
284
+
285
+ @app.command()
286
+ def index(folder: Path, timings: bool = False, include_tests: bool = False):
287
+ folder = folder.resolve()
288
+ if not folder.is_dir():
289
+ error_console.print(f"[b red]Error: [/b red]Not an existing folder: {escape(str(folder))}")
290
+ raise typer.Exit(code=1)
291
+ project_hash = compute_project_hash(folder)
292
+
293
+ registry = safe_load_registry_index_cmds()
294
+
295
+ if project_hash in registry:
296
+ test_status = "test files" if registry[project_hash]["include_tests"] else "no test files"
297
+ console.print(f"Already indexed (with {test_status}): {escape(str(folder))}. Run 'fun reindex' to rebuild.")
298
+ raise typer.Exit(code=0)
299
+
300
+ parser = CodebaseParser(include_tests=include_tests)
301
+
302
+ with console.status("Parsing codebase...", spinner="arc"):
303
+ tp0 = time.perf_counter()
304
+ functions = parser.parse_dir(folder)
305
+ tp1 = time.perf_counter()
306
+
307
+ if parser.skipped_files:
308
+ error_console.print(
309
+ f"[bold yellow]Warning: [/bold yellow]Skipped [cyan]{len(parser.skipped_files)}[/cyan] file(s) "
310
+ f"that could not be parsed (for example syntax errors, unsupported encoding, unreadable files, or very deeply nested code). "
311
+ f"Functions in them will not be searchable."
312
+ )
313
+ console.print()
314
+
315
+ if not functions:
316
+ error_console.print(f"[bold yellow]Warning: [/bold yellow]No functions found in {escape(str(folder))}. Nothing to index.")
317
+ raise typer.Exit(code=1)
318
+
319
+ console.print(f"Parsed [cyan]{len(functions)}[/cyan] functions")
320
+ if timings:
321
+ console.print(f"[dim]Parsing took [cyan]{tp1 - tp0:.2f}[/cyan] seconds.[/dim]")
322
+
323
+ try:
324
+ console.print()
325
+ with console.status("Building BM25, Vector, and Graph indexes...", spinner="arc"):
326
+ from funseek.indexing.bm25_index import BM25Index
327
+ from funseek.indexing.vector_index import VectorIndex
328
+ from funseek.indexing.graph_index import GraphIndex
329
+
330
+ tb0 = time.perf_counter()
331
+ bm25_index = BM25Index.build(functions)
332
+ tb1 = time.perf_counter()
333
+
334
+ tv0 = time.perf_counter()
335
+ vector_index = VectorIndex.build(
336
+ functions,
337
+ persist=True,
338
+ collection_name=project_hash,
339
+ persist_path=CHROMA_DIR,
340
+ )
341
+ tv1 = time.perf_counter()
342
+
343
+ tg0 = time.perf_counter()
344
+ graph_index = GraphIndex.build(functions)
345
+ tg1 = time.perf_counter()
346
+
347
+ if timings:
348
+ console.print(f"[dim]BM25 index built in [cyan]{tb1 - tb0:.2f}[/cyan] seconds.[/dim]")
349
+ console.print(f"[dim]Vector index built in [cyan]{tv1 - tv0:.2f}[/cyan] seconds.[/dim]")
350
+ console.print(f"[dim]Graph index built in [cyan]{tg1 - tg0:.2f}[/cyan] seconds.[/dim]")
351
+ console.print()
352
+
353
+ bm25_index.save(BM25_DIR / f"{project_hash}.pkl")
354
+ graph_index.save(GRAPH_DIR / f"{project_hash}.pkl")
355
+ except Exception as e:
356
+ error_console.print(f"[b red]Error: [/b red]Failed to build indexes: {escape(str(e) or type(e).__name__)}")
357
+ raise typer.Exit(code=1)
358
+
359
+ file_mtimes = get_file_mtimes(folder, include_tests)
360
+ registry[project_hash] = {
361
+ "folder": folder.as_posix(),
362
+ "vector_index_embedding_model": vector_index.model_name,
363
+ "file_mtimes": file_mtimes,
364
+ "include_tests": include_tests,
365
+ }
366
+
367
+ try:
368
+ save_registry(registry)
369
+ except (OSError, TypeError, ValueError) as e:
370
+ error_console.print(
371
+ f"[b red]Error: [/b red]Indexes were built but could not be registered: {escape(str(e))}\n"
372
+ f"Run 'fun reindex {escape(str(folder))}' again to rebuild."
373
+ )
374
+ raise typer.Exit(code=1)
375
+
376
+ console.print(f"[b green]Success: [/b green]Indexed and saved [cyan]{len(functions)}[/cyan] functions from {escape(str(folder))}.")
377
+
378
+
379
+ @app.command()
380
+ def reindex(folder: Path, timings: bool = False, include_tests: bool = False):
381
+ folder = folder.resolve()
382
+ if not folder.is_dir():
383
+ error_console.print(f"[b red]Error: [/b red]Not an existing folder: {escape(str(folder))}")
384
+ raise typer.Exit(code=1)
385
+ project_hash = compute_project_hash(folder)
386
+
387
+ registry = safe_load_registry_index_cmds()
388
+
389
+ parser = CodebaseParser(include_tests=include_tests)
390
+
391
+ with console.status("Parsing codebase...", spinner="arc"):
392
+ tp0 = time.perf_counter()
393
+ functions = parser.parse_dir(folder)
394
+ tp1 = time.perf_counter()
395
+
396
+ if parser.skipped_files:
397
+ error_console.print(
398
+ f"[bold yellow]Warning: [/bold yellow]Skipped [cyan]{len(parser.skipped_files)}[/cyan] file(s) "
399
+ f"that could not be parsed (for example syntax errors, unsupported encoding, unreadable files, or very deeply nested code). "
400
+ f"Functions in them will not be searchable."
401
+ )
402
+
403
+ if not functions:
404
+ error_console.print(f"[bold yellow]Warning: [/bold yellow]No functions found in {escape(str(folder))}. Nothing to index.")
405
+ raise typer.Exit(code=1)
406
+
407
+ console.print(f"Parsed [cyan]{len(functions)}[/cyan] functions")
408
+ if timings:
409
+ console.print(f"[dim]Parsing took [cyan]{tp1 - tp0:.2f}[/cyan] seconds.[/dim]")
410
+
411
+ if project_hash in registry:
412
+ del registry[project_hash]
413
+ try:
414
+ save_registry(registry)
415
+ (BM25_DIR / f"{project_hash}.pkl").unlink(missing_ok=True)
416
+ (GRAPH_DIR / f"{project_hash}.pkl").unlink(missing_ok=True)
417
+ except Exception as e:
418
+ error_console.print(f"[b red]Error: [/b red]Could not clear the old index: {escape(str(e) or type(e).__name__)}")
419
+ raise typer.Exit(code=1)
420
+
421
+ try:
422
+ console.print()
423
+ with console.status("Building BM25, Vector, and Graph indexes...", spinner="arc"):
424
+ from funseek.indexing.bm25_index import BM25Index
425
+ from funseek.indexing.vector_index import VectorIndex
426
+ from funseek.indexing.graph_index import GraphIndex
427
+
428
+ tb0 = time.perf_counter()
429
+ bm25_index = BM25Index.build(functions)
430
+ tb1 = time.perf_counter()
431
+
432
+ tv0 = time.perf_counter()
433
+ vector_index = VectorIndex.build(
434
+ functions,
435
+ persist=True,
436
+ collection_name=project_hash,
437
+ persist_path=CHROMA_DIR,
438
+ )
439
+ tv1 = time.perf_counter()
440
+
441
+ tg0 = time.perf_counter()
442
+ graph_index = GraphIndex.build(functions)
443
+ tg1 = time.perf_counter()
444
+
445
+ if timings:
446
+ console.print(f"[dim]BM25 index built in [cyan]{tb1 - tb0:.2f}[/cyan] seconds.[/dim]")
447
+ console.print(f"[dim]Vector index built in [cyan]{tv1 - tv0:.2f}[/cyan] seconds.[/dim]")
448
+ console.print(f"[dim]Graph index built in [cyan]{tg1 - tg0:.2f}[/cyan] seconds.[/dim]")
449
+ console.print()
450
+
451
+ bm25_index.save(BM25_DIR / f"{project_hash}.pkl")
452
+ graph_index.save(GRAPH_DIR / f"{project_hash}.pkl")
453
+ except Exception as e:
454
+ error_console.print(f"[b red]Error: [/b red]Failed to rebuild indexes: {escape(str(e) or type(e).__name__)}")
455
+ raise typer.Exit(code=1)
456
+
457
+ file_mtimes = get_file_mtimes(folder, include_tests)
458
+
459
+ registry[project_hash] = {
460
+ "folder": folder.as_posix(),
461
+ "vector_index_embedding_model": vector_index.model_name,
462
+ "file_mtimes": file_mtimes,
463
+ "include_tests": include_tests,
464
+ }
465
+
466
+ try:
467
+ save_registry(registry)
468
+ except (OSError, TypeError, ValueError) as e:
469
+ error_console.print(
470
+ f"[b red]Error: [/b red]Indexes were built but could not be registered: {escape(str(e))}\n"
471
+ f"Run 'fun reindex {escape(str(folder))}' again to rebuild."
472
+ )
473
+ raise typer.Exit(code=1)
474
+
475
+ console.print(f"[b green]Success: [/b green]Indexed and saved [cyan]{len(functions)}[/cyan] functions from {escape(str(folder))}.")
476
+
477
+
478
+
479
+ @app.command()
480
+ def search(
481
+ folder: Path,
482
+ no_index: bool = False,
483
+ bm25_weight: float = 0.9,
484
+ vector_weight: float = 1.0,
485
+ structural_weight: float = 0.3,
486
+ max_hop: int = 1,
487
+ decay_factor: float = 0.5,
488
+ provider: str | None = None,
489
+ model: str | None = None,
490
+ top_n: int = 10,
491
+ num_rerank_candids: int = 20,
492
+ timings: bool = False,
493
+ include_tests: bool = False
494
+ ):
495
+ folder = folder.resolve()
496
+ if not folder.is_dir():
497
+ error_console.print(f"[b red]Error: [/b red]Not an existing folder: {escape(str(folder))}")
498
+ raise typer.Exit(code=1)
499
+
500
+ bm25_index, vector_index, graph_index, blt, vlt, glt = get_indexes(folder, no_index=no_index, include_tests=include_tests, timings=timings)
501
+
502
+ if timings:
503
+ action = "build" if no_index else "load"
504
+ console.print(f"[dim]BM25 index {action} took [cyan]{blt:.2f}[/cyan] seconds.[/dim]")
505
+ console.print(f"[dim]Vector index {action} took [cyan]{vlt:.2f}[/cyan] seconds.[/dim]")
506
+ console.print(f"[dim]Graph index {action} took [cyan]{glt:.2f}[/cyan] seconds.[/dim]")
507
+ console.print()
508
+
509
+ from funseek.retrieval.bm25_retriever import BM25Retriever
510
+ from funseek.retrieval.vector_retriever import VectorRetriever
511
+ from funseek.retrieval.graph_retriever import GraphRetriever
512
+
513
+ bm25_retriever = BM25Retriever(bm25_index)
514
+ vector_retriever = VectorRetriever(vector_index)
515
+ graph_retriever = GraphRetriever(graph_index)
516
+ fuser = Fuser(
517
+ bm25_weight=bm25_weight,
518
+ vector_weight=vector_weight,
519
+ structural_weight=structural_weight,
520
+ )
521
+
522
+ reranker, skip_reason = None, None
523
+
524
+ if provider is None:
525
+ skip_reason = "No provider specified."
526
+ elif provider == "gemini":
527
+ with console.status("Setting up provider...", spinner="arc"):
528
+ from funseek import config
529
+
530
+ api_key = config.get_api_key("gemini")
531
+ if api_key is None:
532
+ skip_reason = "No Gemini API key found."
533
+ else:
534
+ reranker = Reranker(provider=GeminiProvider(api_key=api_key, model_name=model), top_n=top_n)
535
+ elif provider == "ollama":
536
+ reranker = Reranker(provider=OllamaProvider(model_name=model), top_n=top_n)
537
+ else:
538
+ skip_reason = f"Unknown provider: {escape(str(provider))}."
539
+
540
+
541
+ while True:
542
+ try:
543
+ query = typer.prompt("Query").strip()
544
+ console.print()
545
+ except typer.Abort:
546
+ break
547
+ if query.lower() in {"exit", "quit"}:
548
+ break
549
+ if not query:
550
+ continue
551
+
552
+ rerank_candidates = search_helper(bm25_retriever, vector_retriever, graph_retriever, fuser, query, max_hop, decay_factor, num_rerank_candids, timings)
553
+
554
+ if not rerank_candidates:
555
+ console.print()
556
+ console.print("No relevant results found.")
557
+ continue
558
+
559
+ final_results = rerank_results(query, rerank_candidates, reranker, skip_reason, top_n, timings)
560
+
561
+ print_results(query, final_results)
562
+
563
+
564
+ @app.command()
565
+ def clear(folder: Path | None = None, all_items: bool = False):
566
+ import shutil
567
+
568
+ if bool(folder) == all_items:
569
+ error_console.print("[b yellow]Warning: [/b yellow]Provide --folder <path> or --all-items.")
570
+ raise typer.Exit(code=1)
571
+
572
+ if all_items:
573
+ try:
574
+ for d in (BM25_DIR, GRAPH_DIR, CHROMA_DIR):
575
+ if d.exists():
576
+ shutil.rmtree(d)
577
+ save_registry({})
578
+ except OSError as e:
579
+ error_console.print(f"[b red]Error: [/b red]Could not clear everything: {escape(str(e))}")
580
+ raise typer.Exit(code=1)
581
+ console.print("[b green]Success: [/b green]Cleared all indexes.")
582
+ return
583
+
584
+ corrupted = False
585
+ try:
586
+ registry = load_registry()
587
+ except CorruptedRegistryError:
588
+ corrupted = True
589
+ registry = {}
590
+ error_console.print("[b yellow]Warning: [/b yellow]Registry is corrupted. Clearing without it.")
591
+
592
+ folder = folder.resolve()
593
+ project_hash = compute_project_hash(folder)
594
+
595
+ if not corrupted and project_hash not in registry:
596
+ error_console.print(f"[b yellow]Warning: [/b yellow]{escape(str(folder))} is not indexed. Nothing to clear.")
597
+ raise typer.Exit(code=0)
598
+
599
+ with console.status("Clearing...", spinner="arc"):
600
+ from funseek.indexing.vector_index import VectorIndex
601
+
602
+ try:
603
+ (BM25_DIR / f"{project_hash}.pkl").unlink(missing_ok=True)
604
+ VectorIndex.delete(collection_name=project_hash, persist_path=CHROMA_DIR)
605
+ (GRAPH_DIR / f"{project_hash}.pkl").unlink(missing_ok=True)
606
+ except Exception as e:
607
+ error_console.print(
608
+ f"[b red]Error: [/b red]Could not fully clear {escape(str(folder))}: {escape(str(e) or type(e).__name__)}."
609
+ )
610
+ raise typer.Exit(code=1)
611
+
612
+ if corrupted:
613
+ error_console.print(
614
+ "[b yellow]Warning: [/b yellow]The registry is corrupted, so it was not updated. "
615
+ f"Any index data for {escape(str(folder))} was deleted. "
616
+ "The next 'index' or 'reindex' may back up the corrupted registry, "
617
+ "and that backup may still list this folder in registry even though its data is gone."
618
+ )
619
+ return
620
+
621
+ del registry[project_hash]
622
+
623
+ try:
624
+ save_registry(registry)
625
+ except (OSError, TypeError, ValueError) as e:
626
+ error_console.print(
627
+ f"[b red]Error: [/b red]Indexes were cleared but failed to update registry: {escape(str(e))}")
628
+ raise typer.Exit(code=1)
629
+
630
+ console.print(f"[b green]Success: [/b green]Cleared indexes for {escape(str(folder))} project.")
631
+
632
+
633
+ @app.command()
634
+ def set_api_key(provider: str, api_key: str):
635
+ from funseek import config
636
+
637
+ if provider not in VALID_KEY_PROVIDERS:
638
+ error_console.print(f"[b red]Error: [/b red]Unknown provider: {escape(str(provider))}. Valid options: {', '.join(VALID_KEY_PROVIDERS)}")
639
+ raise typer.Exit(code=1)
640
+
641
+ if config.set_api_key(provider, api_key):
642
+ console.print(f"[b green]Success: [/b green]API key saved for {escape(str(provider))}.")
643
+ else:
644
+ error_console.print(f"[b red]Error:[/b red] Failed to save API key for {escape(str(provider))}.")
645
+ raise typer.Exit(code=1)
646
+
647
+
648
+ @app.command()
649
+ def get_api_key(provider: str):
650
+ from funseek import config
651
+
652
+ if provider not in VALID_KEY_PROVIDERS:
653
+ error_console.print(f"[b red]Error: [/b red]Unknown provider: {escape(str(provider))}. Valid providers: {', '.join(VALID_KEY_PROVIDERS)}")
654
+ raise typer.Exit(code=1)
655
+
656
+ api_key = config.get_api_key(provider)
657
+ if api_key is None:
658
+ error_console.print(f"No API key configured for {escape(str(provider))}. Run `fun set-api-key {provider} <key>` to set it.")
659
+ else:
660
+ masked = "..." + api_key[-4: ] if len(api_key) > 8 else "..."
661
+ console.print(f"[b green]Success: [/b green]{escape(str(provider))} API key Found: {masked}")
662
+
663
+
664
+ @app.command()
665
+ def clear_api_key(provider: str):
666
+ from funseek import config
667
+
668
+ if provider not in VALID_KEY_PROVIDERS:
669
+ error_console.print(f"[b red]Error: [/b red]Unknown provider: {escape(str(provider))}. Valid providers: {escape(', '.join(VALID_KEY_PROVIDERS))}")
670
+ raise typer.Exit(code=1)
671
+
672
+ if config.clear_api_key(provider):
673
+ console.print(f"[b green]Success: [/b green]API key cleared for {escape(str(provider))}.")
674
+ else:
675
+ error_console.print(f"[b yellow]Warning: [/b yellow]No API key was set for {escape(str(provider))}, or it could not be cleared.")
676
+
677
+
678
+
679
+ if __name__ == "__main__":
680
+ app()