filesonar 0.1.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.
- filesonar/__init__.py +3 -0
- filesonar/chunking.py +43 -0
- filesonar/cli.py +459 -0
- filesonar/config.py +471 -0
- filesonar/db.py +412 -0
- filesonar/drive.py +535 -0
- filesonar/drive_index.py +391 -0
- filesonar/extract.py +351 -0
- filesonar/indexer.py +427 -0
- filesonar/models.py +257 -0
- filesonar/outbox.py +111 -0
- filesonar/pathrules.py +68 -0
- filesonar/search.py +262 -0
- filesonar/server.py +360 -0
- filesonar/skill/SKILL.md +77 -0
- filesonar/watcher.py +104 -0
- filesonar/wizard.py +520 -0
- filesonar-0.1.0.dist-info/METADATA +326 -0
- filesonar-0.1.0.dist-info/RECORD +22 -0
- filesonar-0.1.0.dist-info/WHEEL +4 -0
- filesonar-0.1.0.dist-info/entry_points.txt +2 -0
- filesonar-0.1.0.dist-info/licenses/LICENSE +21 -0
filesonar/__init__.py
ADDED
filesonar/chunking.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Split long text into overlapping chunks that fit an embedding model comfortably."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
_BREAKS = ("\n\n", "\n", ". ", "? ", "! ", "; ", ", ", " ")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _cut_point(text: str, start: int, limit: int) -> int:
|
|
11
|
+
"""Find a natural place to end a chunk that starts at ``start``."""
|
|
12
|
+
end = start + limit
|
|
13
|
+
if end >= len(text):
|
|
14
|
+
return len(text)
|
|
15
|
+
window = text[start:end]
|
|
16
|
+
floor = limit // 2 # never make a chunk shorter than half the limit
|
|
17
|
+
for sep in _BREAKS:
|
|
18
|
+
pos = window.rfind(sep)
|
|
19
|
+
if pos >= floor:
|
|
20
|
+
return start + pos + len(sep)
|
|
21
|
+
return end
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def chunk_text(text: str, size: int, overlap: int) -> list[str]:
|
|
25
|
+
text = text.strip()
|
|
26
|
+
if not text:
|
|
27
|
+
return []
|
|
28
|
+
if len(text) <= size:
|
|
29
|
+
return [text]
|
|
30
|
+
chunks: list[str] = []
|
|
31
|
+
start = 0
|
|
32
|
+
while start < len(text):
|
|
33
|
+
end = _cut_point(text, start, size)
|
|
34
|
+
piece = text[start:end].strip()
|
|
35
|
+
if piece:
|
|
36
|
+
chunks.append(piece)
|
|
37
|
+
if end >= len(text):
|
|
38
|
+
break
|
|
39
|
+
# Step back by the overlap, then forward to a word boundary.
|
|
40
|
+
nxt = max(end - overlap, start + 1)
|
|
41
|
+
match = re.search(r"\s", text[nxt:end])
|
|
42
|
+
start = nxt + match.end() if match else nxt
|
|
43
|
+
return chunks
|
filesonar/cli.py
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
"""Command-line interface: ``filesonar init | doctor | index | search | status | watch |
|
|
2
|
+
serve | drive``."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from . import __version__
|
|
13
|
+
from .config import (
|
|
14
|
+
EXAMPLE_CONFIG,
|
|
15
|
+
Config,
|
|
16
|
+
ConfigError,
|
|
17
|
+
default_config_path,
|
|
18
|
+
load_config,
|
|
19
|
+
write_private,
|
|
20
|
+
)
|
|
21
|
+
from .db import Database
|
|
22
|
+
from .extract import tesseract_available
|
|
23
|
+
from .indexer import Indexer
|
|
24
|
+
from .models import ModelError, OllamaCaptioner, OllamaClient, OllamaEmbedder
|
|
25
|
+
from .search import KINDS, SOURCES, Searcher
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _open(cfg: Config) -> tuple[Database, OllamaClient]:
|
|
29
|
+
return Database(cfg.db_path), OllamaClient(cfg.models)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _drive_indexer(cfg: Config, db: Database, client: OllamaClient, progress=None):
|
|
33
|
+
"""A Drive indexer if Drive is enabled and signed in, else None (with a warning)."""
|
|
34
|
+
if not cfg.drive.enabled:
|
|
35
|
+
return None
|
|
36
|
+
from .drive import DriveClient, NotSignedIn
|
|
37
|
+
from .drive_index import DriveIndexer
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
drive = DriveClient.from_data_dir(cfg.data_dir)
|
|
41
|
+
except NotSignedIn as exc:
|
|
42
|
+
print(f"warning: Google Drive skipped: {exc}", file=sys.stderr)
|
|
43
|
+
return None
|
|
44
|
+
return DriveIndexer(cfg, db, OllamaEmbedder(client), drive, OllamaCaptioner(client), progress)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _print_errors(report) -> None:
|
|
48
|
+
for path, error in report.errors[:20]:
|
|
49
|
+
print(f" failed: {path}: {error}", file=sys.stderr)
|
|
50
|
+
if len(report.errors) > 20:
|
|
51
|
+
print(f" ... and {len(report.errors) - 20} more", file=sys.stderr)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def cmd_init(args: argparse.Namespace) -> int:
|
|
55
|
+
path: Path = args.config or default_config_path()
|
|
56
|
+
if path.exists() and not args.force:
|
|
57
|
+
print(f"{path} already exists (use --force to overwrite)", file=sys.stderr)
|
|
58
|
+
return 1
|
|
59
|
+
write_private(path, EXAMPLE_CONFIG)
|
|
60
|
+
print(f"wrote {path}\nedit the folder list, then run: filesonar index")
|
|
61
|
+
return 0
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def cmd_setup(args: argparse.Namespace) -> int:
|
|
65
|
+
from .wizard import Options, Setup
|
|
66
|
+
|
|
67
|
+
opts = Options(
|
|
68
|
+
config_path=args.config,
|
|
69
|
+
assume_yes=args.yes,
|
|
70
|
+
folders=args.folders,
|
|
71
|
+
vision=args.vision,
|
|
72
|
+
drive_client_secret=args.drive_client_secret,
|
|
73
|
+
openclaw=args.openclaw,
|
|
74
|
+
claude_code=False if args.no_claude_code else None,
|
|
75
|
+
service=False if args.no_service else None,
|
|
76
|
+
index_now=False if args.no_index else None,
|
|
77
|
+
)
|
|
78
|
+
try:
|
|
79
|
+
return Setup(opts).main()
|
|
80
|
+
except KeyboardInterrupt:
|
|
81
|
+
print("\nsetup stopped; run `filesonar setup` again to continue")
|
|
82
|
+
return 130
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def cmd_doctor(cfg: Config) -> int:
|
|
86
|
+
ok = True
|
|
87
|
+
client = OllamaClient(cfg.models)
|
|
88
|
+
installed = client.installed_models()
|
|
89
|
+
print(f"config: {cfg.source}")
|
|
90
|
+
print(f"index: {cfg.db_path}")
|
|
91
|
+
for root in cfg.roots:
|
|
92
|
+
print(f"folder: {root}" + ("" if root.is_dir() else " (missing!)"))
|
|
93
|
+
if not installed:
|
|
94
|
+
print(f"ollama: not reachable at {cfg.models.host}")
|
|
95
|
+
ok = False
|
|
96
|
+
else:
|
|
97
|
+
print(f"ollama: reachable at {cfg.models.host}")
|
|
98
|
+
for label, name, needed in (
|
|
99
|
+
("embeddings", cfg.models.embedding_model, True),
|
|
100
|
+
("vision", cfg.models.vision_model, cfg.models.caption_images),
|
|
101
|
+
):
|
|
102
|
+
if not needed:
|
|
103
|
+
print(f"{label + ':':<12} disabled")
|
|
104
|
+
continue
|
|
105
|
+
present = name in installed
|
|
106
|
+
state = "ok" if present else f"(missing: ollama pull {name})"
|
|
107
|
+
print(f"{label + ':':<12} {name} {state}")
|
|
108
|
+
ok = ok and (present or label == "vision")
|
|
109
|
+
for name, (vram, size) in sorted(client.loaded_models().items()):
|
|
110
|
+
if name.endswith(":latest") or not size or vram >= size:
|
|
111
|
+
continue
|
|
112
|
+
# Ollama splits a model between GPU and CPU when video memory was short at load
|
|
113
|
+
# time; it stays that way (and runs several times slower) until reloaded.
|
|
114
|
+
print(
|
|
115
|
+
f"warning: {name} is only {vram * 100 // size}% in GPU memory and will be "
|
|
116
|
+
f"slow; free GPU memory, then run: ollama stop {name}"
|
|
117
|
+
)
|
|
118
|
+
print(f"tesseract: {'ok' if tesseract_available() else 'missing (no OCR)'}")
|
|
119
|
+
if cfg.drive.enabled:
|
|
120
|
+
from .drive import DriveError, load_token, token_path
|
|
121
|
+
|
|
122
|
+
try:
|
|
123
|
+
account = load_token(token_path(cfg.data_dir)).account
|
|
124
|
+
print(f"drive: signed in as {account}")
|
|
125
|
+
except DriveError as exc:
|
|
126
|
+
print(f"drive: {exc}")
|
|
127
|
+
ok = False
|
|
128
|
+
else:
|
|
129
|
+
print("drive: disabled")
|
|
130
|
+
return 0 if ok else 1
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _progress_printer(verbose: bool):
|
|
134
|
+
"""Every file in verbose mode; otherwise a short line every 50 files."""
|
|
135
|
+
count = 0
|
|
136
|
+
|
|
137
|
+
def show(message: str) -> None:
|
|
138
|
+
nonlocal count
|
|
139
|
+
count += 1
|
|
140
|
+
if verbose:
|
|
141
|
+
print(message, file=sys.stderr)
|
|
142
|
+
elif count % 50 == 0:
|
|
143
|
+
print(f"... {count} files read", file=sys.stderr, flush=True)
|
|
144
|
+
|
|
145
|
+
return show
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def cmd_index(cfg: Config, args: argparse.Namespace) -> int:
|
|
149
|
+
db, client = _open(cfg)
|
|
150
|
+
try:
|
|
151
|
+
if args.rebuild:
|
|
152
|
+
db.reset()
|
|
153
|
+
progress = _progress_printer(args.verbose)
|
|
154
|
+
indexer = Indexer(cfg, db, OllamaEmbedder(client), OllamaCaptioner(client), progress)
|
|
155
|
+
report = indexer.run()
|
|
156
|
+
print(report.summary())
|
|
157
|
+
_print_errors(report)
|
|
158
|
+
drive = _drive_indexer(cfg, db, client, progress)
|
|
159
|
+
if drive is not None:
|
|
160
|
+
drive_report = drive.sync(full=args.rebuild)
|
|
161
|
+
print("Google Drive: " + drive_report.summary())
|
|
162
|
+
_print_errors(drive_report)
|
|
163
|
+
finally:
|
|
164
|
+
db.close()
|
|
165
|
+
return 0
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def cmd_search(cfg: Config, args: argparse.Namespace) -> int:
|
|
169
|
+
db, client = _open(cfg)
|
|
170
|
+
try:
|
|
171
|
+
searcher = Searcher(db, OllamaEmbedder(client), cfg.search)
|
|
172
|
+
hits = searcher.search(
|
|
173
|
+
" ".join(args.query),
|
|
174
|
+
limit=args.limit,
|
|
175
|
+
kind=args.kind,
|
|
176
|
+
folder=args.folder,
|
|
177
|
+
modified_after=args.after,
|
|
178
|
+
modified_before=args.before,
|
|
179
|
+
source=args.source,
|
|
180
|
+
)
|
|
181
|
+
finally:
|
|
182
|
+
db.close()
|
|
183
|
+
if searcher.last_warning:
|
|
184
|
+
print(f"warning: {searcher.last_warning}", file=sys.stderr)
|
|
185
|
+
if args.json:
|
|
186
|
+
print(json.dumps([h.to_dict() for h in hits], indent=2, ensure_ascii=False))
|
|
187
|
+
return 0
|
|
188
|
+
if not hits:
|
|
189
|
+
print("no matches")
|
|
190
|
+
return 0
|
|
191
|
+
for n, hit in enumerate(hits, 1):
|
|
192
|
+
page = f" p.{hit.page}" if hit.page else ""
|
|
193
|
+
where = f"Google Drive: {hit.location}/{hit.name}" if hit.source == "drive" else hit.path
|
|
194
|
+
print(f"{n}. {where}{page}\n {hit.kind}, {hit.modified}, matched in {hit.matched_in}")
|
|
195
|
+
print(f" {hit.snippet}\n")
|
|
196
|
+
return 0
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def cmd_status(cfg: Config) -> int:
|
|
200
|
+
db = Database(cfg.db_path)
|
|
201
|
+
try:
|
|
202
|
+
print(json.dumps(db.stats(), indent=2))
|
|
203
|
+
finally:
|
|
204
|
+
db.close()
|
|
205
|
+
return 0
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def cmd_watch(cfg: Config, args: argparse.Namespace) -> int:
|
|
209
|
+
from .watcher import watch
|
|
210
|
+
|
|
211
|
+
db, client = _open(cfg)
|
|
212
|
+
indexer = Indexer(cfg, db, OllamaEmbedder(client), OllamaCaptioner(client))
|
|
213
|
+
drive = _drive_indexer(cfg, db, client)
|
|
214
|
+
try:
|
|
215
|
+
if not args.no_initial_scan:
|
|
216
|
+
logging.info("initial scan: %s", indexer.run().summary())
|
|
217
|
+
watch(
|
|
218
|
+
indexer,
|
|
219
|
+
full_scan_hours=args.full_scan_hours,
|
|
220
|
+
drive=drive,
|
|
221
|
+
drive_poll_minutes=cfg.drive.poll_minutes,
|
|
222
|
+
)
|
|
223
|
+
except KeyboardInterrupt:
|
|
224
|
+
pass
|
|
225
|
+
finally:
|
|
226
|
+
db.close()
|
|
227
|
+
return 0
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _drive_factory(cfg: Config):
|
|
231
|
+
def make():
|
|
232
|
+
from .drive import DriveClient
|
|
233
|
+
|
|
234
|
+
return DriveClient.from_data_dir(cfg.data_dir)
|
|
235
|
+
|
|
236
|
+
return make if cfg.drive.enabled else None
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def cmd_serve(cfg: Config) -> int:
|
|
240
|
+
from .server import build_server
|
|
241
|
+
|
|
242
|
+
db, client = _open(cfg)
|
|
243
|
+
try:
|
|
244
|
+
build_server(cfg, db, OllamaEmbedder(client), drive=_drive_factory(cfg)).run("stdio")
|
|
245
|
+
finally:
|
|
246
|
+
db.close()
|
|
247
|
+
return 0
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def cmd_drive(cfg: Config, args: argparse.Namespace) -> int:
|
|
251
|
+
import httpx
|
|
252
|
+
|
|
253
|
+
from .drive import (
|
|
254
|
+
DriveClient,
|
|
255
|
+
DriveError,
|
|
256
|
+
NotSignedIn,
|
|
257
|
+
sign_in,
|
|
258
|
+
token_path,
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
path = token_path(cfg.data_dir)
|
|
262
|
+
if args.drive_command == "login":
|
|
263
|
+
token = sign_in(cfg.data_dir, args.client_secret, open_browser=not args.no_browser)
|
|
264
|
+
print(f"signed in as {token.account}; token saved to {path}")
|
|
265
|
+
if not cfg.drive.enabled:
|
|
266
|
+
print(f"now set `enabled = true` under [drive] in {cfg.source}")
|
|
267
|
+
db = Database(cfg.db_path)
|
|
268
|
+
try:
|
|
269
|
+
first_time = not db.stats().get("drive_files")
|
|
270
|
+
finally:
|
|
271
|
+
db.close()
|
|
272
|
+
if first_time:
|
|
273
|
+
print("then run: filesonar index")
|
|
274
|
+
return 0
|
|
275
|
+
|
|
276
|
+
if args.drive_command == "logout":
|
|
277
|
+
try:
|
|
278
|
+
client = DriveClient.from_data_dir(cfg.data_dir)
|
|
279
|
+
except NotSignedIn:
|
|
280
|
+
print("not signed in")
|
|
281
|
+
return 0
|
|
282
|
+
try:
|
|
283
|
+
client.revoke()
|
|
284
|
+
except (httpx.HTTPError, DriveError) as exc:
|
|
285
|
+
print(
|
|
286
|
+
f"warning: could not reach Google to revoke access ({exc}); remove "
|
|
287
|
+
"filesonar at https://myaccount.google.com/permissions",
|
|
288
|
+
file=sys.stderr,
|
|
289
|
+
)
|
|
290
|
+
finally:
|
|
291
|
+
client.close()
|
|
292
|
+
path.unlink(missing_ok=True)
|
|
293
|
+
db = Database(cfg.db_path)
|
|
294
|
+
try:
|
|
295
|
+
removed = 0
|
|
296
|
+
for key in db.all_paths("drive"):
|
|
297
|
+
removed += db.delete_path(key)
|
|
298
|
+
for key in ("drive_page_token", "drive_last_full", "drive_share_folder"):
|
|
299
|
+
db.conn.execute("DELETE FROM meta WHERE key = ?", (key,))
|
|
300
|
+
db.conn.commit()
|
|
301
|
+
finally:
|
|
302
|
+
db.close()
|
|
303
|
+
print(f"signed out; access revoked and {removed} Drive entries removed from the index")
|
|
304
|
+
return 0
|
|
305
|
+
|
|
306
|
+
if args.drive_command == "status":
|
|
307
|
+
try:
|
|
308
|
+
client = DriveClient.from_data_dir(cfg.data_dir)
|
|
309
|
+
account = client.token.account or "(unknown account)"
|
|
310
|
+
client.close()
|
|
311
|
+
except NotSignedIn:
|
|
312
|
+
account = None
|
|
313
|
+
db = Database(cfg.db_path)
|
|
314
|
+
try:
|
|
315
|
+
count = len(db.all_paths("drive"))
|
|
316
|
+
last = db.get_meta("drive_last_full")
|
|
317
|
+
finally:
|
|
318
|
+
db.close()
|
|
319
|
+
print(f"enabled: {cfg.drive.enabled}")
|
|
320
|
+
print(f"signed in: {account or 'no (run: filesonar drive login)'}")
|
|
321
|
+
print(f"indexed: {count} files")
|
|
322
|
+
if last:
|
|
323
|
+
from datetime import datetime
|
|
324
|
+
|
|
325
|
+
print(
|
|
326
|
+
f"full sync: {datetime.fromtimestamp(float(last)).isoformat(timespec='minutes')}"
|
|
327
|
+
)
|
|
328
|
+
return 0
|
|
329
|
+
|
|
330
|
+
# sync
|
|
331
|
+
if not cfg.drive.enabled:
|
|
332
|
+
print(f"Google Drive is disabled; set `enabled = true` under [drive] in {cfg.source}")
|
|
333
|
+
return 1
|
|
334
|
+
db, client = _open(cfg)
|
|
335
|
+
try:
|
|
336
|
+
drive = _drive_indexer(cfg, db, client, _progress_printer(args.verbose))
|
|
337
|
+
if drive is None:
|
|
338
|
+
return 1
|
|
339
|
+
report = drive.sync(full=args.full)
|
|
340
|
+
finally:
|
|
341
|
+
db.close()
|
|
342
|
+
print("Google Drive: " + report.summary())
|
|
343
|
+
_print_errors(report)
|
|
344
|
+
return 0
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
348
|
+
p = argparse.ArgumentParser(
|
|
349
|
+
prog="filesonar", description="Search your files by what is inside them."
|
|
350
|
+
)
|
|
351
|
+
p.add_argument("--version", action="version", version=f"filesonar {__version__}")
|
|
352
|
+
p.add_argument(
|
|
353
|
+
"-c", "--config", type=Path, help="config file (default: %(default)s)", default=None
|
|
354
|
+
)
|
|
355
|
+
p.add_argument("-v", "--verbose", action="store_true", help="show more detail")
|
|
356
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
357
|
+
|
|
358
|
+
s = sub.add_parser("init", help="write a starter config file")
|
|
359
|
+
s.add_argument("--force", action="store_true", help="overwrite an existing config")
|
|
360
|
+
|
|
361
|
+
s = sub.add_parser(
|
|
362
|
+
"setup",
|
|
363
|
+
help="set everything up: models, config, agents, background indexing",
|
|
364
|
+
description="Check and set up everything filesonar needs. Safe to run again: "
|
|
365
|
+
"only what is missing is changed.",
|
|
366
|
+
)
|
|
367
|
+
s.add_argument("-y", "--yes", action="store_true", help="accept every default answer")
|
|
368
|
+
s.add_argument(
|
|
369
|
+
"--folder", dest="folders", action="append", type=Path, default=[], metavar="PATH",
|
|
370
|
+
help="a folder to search (repeat for more); default: Documents, Pictures, ...",
|
|
371
|
+
) # fmt: skip
|
|
372
|
+
s.add_argument(
|
|
373
|
+
"--vision", action=argparse.BooleanOptionalAction, default=None,
|
|
374
|
+
help="download the vision model that describes photos (about 6 GB)",
|
|
375
|
+
) # fmt: skip
|
|
376
|
+
s.add_argument(
|
|
377
|
+
"--drive-client-secret",
|
|
378
|
+
type=Path,
|
|
379
|
+
metavar="JSON",
|
|
380
|
+
help="connect Google Drive with this file",
|
|
381
|
+
)
|
|
382
|
+
s.add_argument("--openclaw", metavar="PATH", help="path to the openclaw command")
|
|
383
|
+
s.add_argument("--no-claude-code", action="store_true", help="do not add to Claude Code")
|
|
384
|
+
s.add_argument("--no-service", action="store_true", help="no background indexing service")
|
|
385
|
+
s.add_argument("--no-index", action="store_true", help="do not index right away")
|
|
386
|
+
|
|
387
|
+
sub.add_parser("doctor", help="check models, OCR and folders")
|
|
388
|
+
|
|
389
|
+
s = sub.add_parser("index", help="index new and changed files")
|
|
390
|
+
s.add_argument("--rebuild", action="store_true", help="start from an empty index")
|
|
391
|
+
|
|
392
|
+
s = sub.add_parser("search", help="search the index")
|
|
393
|
+
s.add_argument("query", nargs="+")
|
|
394
|
+
s.add_argument("-n", "--limit", type=int, default=8)
|
|
395
|
+
s.add_argument("-k", "--kind", choices=KINDS)
|
|
396
|
+
s.add_argument("--folder", help="only files inside this folder")
|
|
397
|
+
s.add_argument("--after", help="modified on or after YYYY-MM-DD")
|
|
398
|
+
s.add_argument("--before", help="modified on or before YYYY-MM-DD")
|
|
399
|
+
s.add_argument("--source", choices=SOURCES, help="only local files or only Google Drive")
|
|
400
|
+
s.add_argument("--json", action="store_true", help="machine-readable output")
|
|
401
|
+
|
|
402
|
+
sub.add_parser("status", help="show index statistics")
|
|
403
|
+
|
|
404
|
+
s = sub.add_parser("watch", help="keep the index up to date as files change")
|
|
405
|
+
s.add_argument("--no-initial-scan", action="store_true")
|
|
406
|
+
s.add_argument("--full-scan-hours", type=float, default=24.0)
|
|
407
|
+
|
|
408
|
+
sub.add_parser("serve", help="run the MCP server on stdio (for AI agents)")
|
|
409
|
+
|
|
410
|
+
s = sub.add_parser("drive", help="Google Drive: sign in, sync, status, sign out")
|
|
411
|
+
drive = s.add_subparsers(dest="drive_command", required=True)
|
|
412
|
+
d = drive.add_parser("login", help="sign in with your own Google OAuth client")
|
|
413
|
+
d.add_argument(
|
|
414
|
+
"--client-secret",
|
|
415
|
+
type=Path,
|
|
416
|
+
help="the client_secret_*.json downloaded from Google Cloud Console (needed the "
|
|
417
|
+
"first time; signing in again reuses the saved client)",
|
|
418
|
+
)
|
|
419
|
+
d.add_argument("--no-browser", action="store_true", help="only print the sign-in link")
|
|
420
|
+
d = drive.add_parser("sync", help="fetch changes from Drive now")
|
|
421
|
+
d.add_argument("--full", action="store_true", help="re-list every file")
|
|
422
|
+
drive.add_parser("status", help="show the Drive connection and what is indexed")
|
|
423
|
+
drive.add_parser("logout", help="revoke access and remove Drive files from the index")
|
|
424
|
+
return p
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def main(argv: list[str] | None = None) -> int:
|
|
428
|
+
args = build_parser().parse_args(argv)
|
|
429
|
+
# stdout belongs to the MCP protocol in `serve`, so logs always go to stderr.
|
|
430
|
+
logging.basicConfig(
|
|
431
|
+
level=logging.DEBUG if args.verbose else logging.INFO,
|
|
432
|
+
format="%(levelname)s %(message)s",
|
|
433
|
+
stream=sys.stderr,
|
|
434
|
+
)
|
|
435
|
+
for noisy in ("httpx", "httpcore", "PIL", "watchdog", "pytesseract"):
|
|
436
|
+
logging.getLogger(noisy).setLevel(logging.WARNING)
|
|
437
|
+
if args.command == "init":
|
|
438
|
+
return cmd_init(args)
|
|
439
|
+
if args.command == "setup":
|
|
440
|
+
return cmd_setup(args)
|
|
441
|
+
try:
|
|
442
|
+
cfg = load_config(args.config)
|
|
443
|
+
handlers = {
|
|
444
|
+
"doctor": lambda: cmd_doctor(cfg),
|
|
445
|
+
"index": lambda: cmd_index(cfg, args),
|
|
446
|
+
"search": lambda: cmd_search(cfg, args),
|
|
447
|
+
"status": lambda: cmd_status(cfg),
|
|
448
|
+
"watch": lambda: cmd_watch(cfg, args),
|
|
449
|
+
"serve": lambda: cmd_serve(cfg),
|
|
450
|
+
"drive": lambda: cmd_drive(cfg, args),
|
|
451
|
+
}
|
|
452
|
+
return handlers[args.command]()
|
|
453
|
+
except (ConfigError, ModelError, ValueError, RuntimeError) as exc:
|
|
454
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
455
|
+
return 2
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
if __name__ == "__main__":
|
|
459
|
+
sys.exit(main())
|