File size: 21,116 Bytes
c4ef1cf
 
 
 
 
 
 
 
 
 
 
 
9513cca
c4ef1cf
 
9513cca
c4ef1cf
 
 
 
 
 
9513cca
 
c4ef1cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9513cca
c4ef1cf
 
9513cca
c4ef1cf
9513cca
c4ef1cf
 
9513cca
c4ef1cf
 
 
 
9513cca
c4ef1cf
 
 
 
 
9513cca
c4ef1cf
 
 
 
9513cca
c4ef1cf
9513cca
c4ef1cf
 
 
 
9513cca
c4ef1cf
 
 
 
 
 
 
9513cca
c4ef1cf
 
 
 
 
 
9513cca
c4ef1cf
 
9513cca
 
 
 
c4ef1cf
 
 
9513cca
c4ef1cf
 
 
 
 
 
 
 
 
 
 
 
 
9513cca
c4ef1cf
9513cca
 
 
c4ef1cf
 
 
 
 
 
9513cca
c4ef1cf
 
 
9513cca
c4ef1cf
 
 
 
 
 
 
 
9513cca
c4ef1cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9513cca
c4ef1cf
 
 
 
 
 
 
 
 
9513cca
c4ef1cf
 
 
 
 
 
 
 
 
9513cca
 
 
c4ef1cf
 
9513cca
c4ef1cf
 
 
 
9513cca
c4ef1cf
9513cca
c4ef1cf
 
 
 
9513cca
c4ef1cf
 
 
 
 
 
9513cca
c4ef1cf
 
 
9513cca
c4ef1cf
 
9513cca
c4ef1cf
 
 
 
 
9513cca
c4ef1cf
 
 
 
 
 
 
 
9513cca
 
 
 
c4ef1cf
9513cca
 
 
 
c4ef1cf
 
 
 
 
 
9513cca
c4ef1cf
 
 
9513cca
c4ef1cf
 
9513cca
 
 
c4ef1cf
9513cca
c4ef1cf
 
 
 
 
 
 
 
 
 
9513cca
c4ef1cf
 
 
9513cca
c4ef1cf
 
 
 
 
 
 
 
9513cca
c4ef1cf
2d72662
c4ef1cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9513cca
c4ef1cf
 
 
 
 
9513cca
c4ef1cf
 
 
 
9513cca
c4ef1cf
 
9513cca
c4ef1cf
 
 
 
 
 
 
 
 
 
9513cca
c4ef1cf
9513cca
 
 
 
c4ef1cf
 
 
 
 
 
9513cca
c4ef1cf
 
 
9513cca
c4ef1cf
 
 
 
 
 
 
 
9513cca
c4ef1cf
 
9513cca
c4ef1cf
 
 
9513cca
c4ef1cf
 
 
9513cca
c4ef1cf
 
 
 
9513cca
c4ef1cf
 
 
 
 
9513cca
c4ef1cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9513cca
c4ef1cf
 
9513cca
c4ef1cf
 
9513cca
c4ef1cf
 
9513cca
c4ef1cf
 
 
 
 
9513cca
c4ef1cf
9513cca
c4ef1cf
 
 
 
 
 
 
 
 
9513cca
c4ef1cf
 
9513cca
 
 
c4ef1cf
 
9513cca
c4ef1cf
 
9513cca
 
 
 
c4ef1cf
9513cca
 
c4ef1cf
9513cca
c4ef1cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9513cca
 
 
c4ef1cf
 
9513cca
c4ef1cf
 
9513cca
c4ef1cf
 
9513cca
 
 
c4ef1cf
 
9513cca
c4ef1cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9513cca
c4ef1cf
 
 
 
 
 
 
9513cca
c4ef1cf
9513cca
c4ef1cf
 
9513cca
c4ef1cf
 
 
 
 
 
 
 
9513cca
c4ef1cf
9513cca
 
 
c4ef1cf
9513cca
c4ef1cf
 
9513cca
c4ef1cf
 
9513cca
 
 
c4ef1cf
9513cca
c4ef1cf
9513cca
 
 
c4ef1cf
9513cca
c4ef1cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9513cca
c4ef1cf
 
 
 
 
 
 
 
9513cca
c4ef1cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9513cca
c4ef1cf
 
9513cca
c4ef1cf
9513cca
c4ef1cf
 
 
9513cca
c4ef1cf
 
 
 
 
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
#!/usr/bin/env python3
"""
Visual RAG Toolkit CLI

Provides command-line interface for:
- Processing PDFs (embedding, Cloudinary upload, Qdrant indexing)
- Searching documents
- Managing collections

Usage:
    # Process PDFs (like process_pdfs_saliency_v2.py)
    visual-rag process --reports-dir ./pdfs --metadata-file metadata.json

    # Search
    visual-rag search --query "budget allocation" --collection my_docs

    # Show collection info
    visual-rag info --collection my_docs
"""

import argparse
import logging
import os
import sys
from pathlib import Path
from urllib.parse import urlparse

from dotenv import load_dotenv

logger = logging.getLogger(__name__)


def setup_logging(debug: bool = False):
    """Configure logging."""
    level = logging.DEBUG if debug else logging.INFO
    logging.basicConfig(
        level=level,
        format="%(asctime)s - %(levelname)s - %(message)s",
        force=True,
    )


def cmd_process(args):
    """
    Process PDFs: convert β†’ embed β†’ upload to Cloudinary β†’ index in Qdrant.

    Equivalent to process_pdfs_saliency_v2.py
    """
    from visual_rag import CloudinaryUploader, QdrantIndexer, VisualEmbedder, load_config
    from visual_rag.indexing.pipeline import ProcessingPipeline

    # Load environment
    load_dotenv()

    # Load config
    config = {}
    if args.config and Path(args.config).exists():
        config = load_config(args.config)

    # Get PDFs
    reports_dir = Path(args.reports_dir)
    if not reports_dir.exists():
        logger.error(f"❌ Reports directory not found: {reports_dir}")
        sys.exit(1)

    pdf_paths = sorted(reports_dir.glob("*.pdf")) + sorted(reports_dir.glob("*.PDF"))
    if not pdf_paths:
        logger.error(f"❌ No PDF files found in: {reports_dir}")
        sys.exit(1)

    logger.info(f"πŸ“ Found {len(pdf_paths)} PDF files")

    # Load metadata mapping
    metadata_mapping = {}
    if args.metadata_file:
        metadata_mapping = ProcessingPipeline.load_metadata_mapping(Path(args.metadata_file))

    # Dry run - just show summary
    if args.dry_run:
        logger.info("πŸƒ DRY RUN MODE")
        logger.info(f"   PDFs: {len(pdf_paths)}")
        logger.info(f"   Metadata entries: {len(metadata_mapping)}")
        logger.info(f"   Collection: {args.collection}")
        logger.info(f"   Cloudinary: {'ENABLED' if not args.no_cloudinary else 'DISABLED'}")

        for pdf in pdf_paths[:10]:
            has_meta = "βœ“" if pdf.stem.lower() in metadata_mapping else "βœ—"
            logger.info(f"   {has_meta} {pdf.name}")
        if len(pdf_paths) > 10:
            logger.info(f"   ... and {len(pdf_paths) - 10} more")
        return

    # Get settings
    model_name = args.model or config.get("model", {}).get("name", "vidore/colSmol-500M")
    collection_name = args.collection or config.get("qdrant", {}).get(
        "collection_name", "visual_documents"
    )

    torch_dtype = None
    if args.torch_dtype != "auto":
        import torch

        torch_dtype = {
            "float32": torch.float32,
            "float16": torch.float16,
            "bfloat16": torch.bfloat16,
        }[args.torch_dtype]

    logger.info(f"πŸ€– Initializing embedder: {model_name}")
    embedder = VisualEmbedder(
        model_name=model_name,
        batch_size=args.batch_size,
        torch_dtype=torch_dtype,
        processor_speed=str(getattr(args, "processor_speed", "fast")),
    )

    # Initialize Qdrant indexer
    qdrant_url = (
        os.getenv("SIGIR_QDRANT_URL") or os.getenv("DEST_QDRANT_URL") or os.getenv("QDRANT_URL")
    )
    qdrant_api_key = (
        os.getenv("SIGIR_QDRANT_KEY")
        or os.getenv("SIGIR_QDRANT_API_KEY")
        or os.getenv("DEST_QDRANT_API_KEY")
        or os.getenv("QDRANT_API_KEY")
    )

    if not qdrant_url:
        logger.error("❌ QDRANT_URL environment variable not set")
        sys.exit(1)

    logger.info(f"πŸ”Œ Connecting to Qdrant: {qdrant_url}")
    indexer = QdrantIndexer(
        url=qdrant_url,
        api_key=qdrant_api_key,
        collection_name=collection_name,
        prefer_grpc=args.prefer_grpc,
        vector_datatype=args.qdrant_vector_dtype,
    )

    # Create collection if needed
    indexer.create_collection(force_recreate=args.force_recreate)
    inferred_fields = []
    inferred_fields.append({"field": "filename", "type": "keyword"})
    inferred_fields.append({"field": "page_number", "type": "integer"})
    inferred_fields.append({"field": "has_text", "type": "bool"})

    if metadata_mapping:
        keys = set()
        for _, meta in metadata_mapping.items():
            if isinstance(meta, dict):
                keys.update(meta.keys())
        for k in sorted(keys):
            if k in ("filename", "page_number", "has_text"):
                continue
            inferred_type = "keyword"
            for _, meta in metadata_mapping.items():
                if not isinstance(meta, dict):
                    continue
                v = meta.get(k)
                if isinstance(v, bool):
                    inferred_type = "bool"
                    break
                if isinstance(v, int):
                    inferred_type = "integer"
                    break
                if isinstance(v, float):
                    inferred_type = "float"
                    break
            inferred_fields.append({"field": k, "type": inferred_type})

    indexer.create_payload_indexes(fields=inferred_fields)

    # Initialize Cloudinary uploader (optional)
    cloudinary_uploader = None
    if not args.no_cloudinary:
        try:
            project_name = config.get("project_name", "visual_docs")
            cloudinary_uploader = CloudinaryUploader(folder=project_name)
        except ValueError as e:
            logger.warning(f"⚠️ Cloudinary not configured: {e}")
            logger.warning("   Continuing without Cloudinary uploads")

    # Create pipeline
    pipeline = ProcessingPipeline(
        embedder=embedder,
        indexer=indexer,
        cloudinary_uploader=cloudinary_uploader,
        metadata_mapping=metadata_mapping,
        config=config,
        embedding_strategy=args.strategy,
        crop_empty=bool(getattr(args, "crop_empty", False)),
        crop_empty_percentage_to_remove=float(
            getattr(args, "crop_empty_percentage_to_remove", 0.9)
        ),
        crop_empty_remove_page_number=bool(getattr(args, "crop_empty_remove_page_number", False)),
    )

    # Process PDFs
    total_uploaded = 0
    total_skipped = 0
    total_failed = 0

    skip_existing = not args.no_skip_existing

    for pdf_idx, pdf_path in enumerate(pdf_paths, 1):
        logger.info(f"\n{'='*60}")
        logger.info(f"πŸ“„ [{pdf_idx}/{len(pdf_paths)}] {pdf_path.name}")
        logger.info(f"{'='*60}")

        result = pipeline.process_pdf(
            pdf_path,
            skip_existing=skip_existing,
            upload_to_cloudinary=(not args.no_cloudinary),
            upload_to_qdrant=True,
        )

        total_uploaded += result["uploaded"]
        total_skipped += result["skipped"]
        total_failed += result["failed"]

    # Summary
    logger.info(f"\n{'='*60}")
    logger.info("πŸ“Š SUMMARY")
    logger.info(f"{'='*60}")
    logger.info(f"   Total PDFs: {len(pdf_paths)}")
    logger.info(f"   Uploaded: {total_uploaded}")
    logger.info(f"   Skipped: {total_skipped}")
    logger.info(f"   Failed: {total_failed}")

    info = indexer.get_collection_info()
    if info:
        logger.info(f"   Collection points: {info.get('points_count', 'N/A')}")


def cmd_search(args):
    """Search documents."""
    from qdrant_client import QdrantClient

    from visual_rag import VisualEmbedder
    from visual_rag.retrieval import SingleStageRetriever, TwoStageRetriever

    load_dotenv()

    qdrant_url = (
        os.getenv("SIGIR_QDRANT_URL") or os.getenv("DEST_QDRANT_URL") or os.getenv("QDRANT_URL")
    )
    qdrant_api_key = (
        os.getenv("SIGIR_QDRANT_KEY")
        or os.getenv("SIGIR_QDRANT_API_KEY")
        or os.getenv("DEST_QDRANT_API_KEY")
        or os.getenv("QDRANT_API_KEY")
    )

    if not qdrant_url:
        logger.error("❌ QDRANT_URL not set")
        sys.exit(1)

    # Initialize
    logger.info(f"πŸ€– Loading model: {args.model}")
    embedder = VisualEmbedder(
        model_name=args.model, processor_speed=str(getattr(args, "processor_speed", "fast"))
    )

    logger.info("πŸ”Œ Connecting to Qdrant")
    grpc_port = 6334 if args.prefer_grpc and urlparse(qdrant_url).port == 6333 else None
    client = QdrantClient(
        url=qdrant_url,
        api_key=qdrant_api_key,
        prefer_grpc=args.prefer_grpc,
        grpc_port=grpc_port,
        check_compatibility=False,
    )
    two_stage = TwoStageRetriever(client, args.collection)
    single_stage = SingleStageRetriever(client, args.collection)

    # Embed query
    logger.info(f"πŸ” Query: {args.query}")
    query_embedding = embedder.embed_query(args.query)

    # Build filter
    filter_obj = None
    if args.year or args.source or args.district:
        filter_obj = two_stage.build_filter(
            year=args.year,
            source=args.source,
            district=args.district,
        )

    # Search
    query_np = query_embedding.detach().cpu().float().numpy()  # .float() for BFloat16
    if args.strategy == "single_full":
        results = single_stage.search(
            query_embedding=query_np,
            top_k=args.top_k,
            strategy="multi_vector",
            filter_obj=filter_obj,
        )
    elif args.strategy == "single_tiles":
        results = single_stage.search(
            query_embedding=query_np,
            top_k=args.top_k,
            strategy="tiles_maxsim",
            filter_obj=filter_obj,
        )
    elif args.strategy == "single_global":
        results = single_stage.search(
            query_embedding=query_np,
            top_k=args.top_k,
            strategy="pooled_global",
            filter_obj=filter_obj,
        )
    else:
        results = two_stage.search(
            query_embedding=query_np,
            top_k=args.top_k,
            prefetch_k=args.prefetch_k,
            filter_obj=filter_obj,
            stage1_mode=args.stage1_mode,
        )

    # Display results
    logger.info(f"\nπŸ“Š Results ({len(results)}):")
    for i, result in enumerate(results, 1):
        payload = result.get("payload", {})
        score = result.get("score_final", result.get("score_stage1", 0))

        filename = payload.get("filename", "N/A")
        page_num = payload.get("page_number", "N/A")
        year = payload.get("year", "N/A")
        source = payload.get("source", "N/A")

        logger.info(f"  {i}. {filename} p.{page_num}")
        logger.info(f"     Score: {score:.4f} | Year: {year} | Source: {source}")

        # Text snippet
        text = payload.get("text", "")
        if text and args.show_text:
            snippet = text[:200].replace("\n", " ")
            logger.info(f"     Text: {snippet}...")


def cmd_info(args):
    """Show collection info."""
    from qdrant_client import QdrantClient

    load_dotenv()

    qdrant_url = (
        os.getenv("SIGIR_QDRANT_URL") or os.getenv("DEST_QDRANT_URL") or os.getenv("QDRANT_URL")
    )
    qdrant_api_key = (
        os.getenv("SIGIR_QDRANT_KEY")
        or os.getenv("SIGIR_QDRANT_API_KEY")
        or os.getenv("DEST_QDRANT_API_KEY")
        or os.getenv("QDRANT_API_KEY")
    )

    if not qdrant_url:
        logger.error("❌ QDRANT_URL not set")
        sys.exit(1)

    grpc_port = 6334 if args.prefer_grpc and urlparse(qdrant_url).port == 6333 else None
    client = QdrantClient(
        url=qdrant_url,
        api_key=qdrant_api_key,
        prefer_grpc=args.prefer_grpc,
        grpc_port=grpc_port,
        check_compatibility=False,
    )

    try:
        info = client.get_collection(args.collection)

        status = info.status
        if hasattr(status, "value"):
            status = status.value

        indexed_count = getattr(info, "indexed_vectors_count", 0) or 0
        if isinstance(indexed_count, dict):
            indexed_count = sum(indexed_count.values())

        logger.info(f"πŸ“Š Collection: {args.collection}")
        logger.info(f"   Status: {status}")
        logger.info(f"   Points: {info.points_count}")
        logger.info(f"   Indexed vectors: {indexed_count}")

        # Show vector config
        if hasattr(info, "config") and hasattr(info.config, "params"):
            vectors = getattr(info.config.params, "vectors", {})
            if vectors:
                logger.info(f"   Vectors: {list(vectors.keys())}")

    except Exception as e:
        logger.error(f"❌ Could not get collection info: {e}")
        sys.exit(1)


def main():
    """Main CLI entry point."""
    parser = argparse.ArgumentParser(
        prog="visual-rag",
        description="Visual RAG Toolkit - Visual document retrieval with ColPali",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Process PDFs (like process_pdfs_saliency_v2.py)
  visual-rag process --reports-dir ./pdfs --metadata-file metadata.json

  # Process without Cloudinary
  visual-rag process --reports-dir ./pdfs --no-cloudinary

  # Search
  visual-rag search --query "budget allocation" --collection my_docs

  # Search with filters
  visual-rag search --query "budget" --year 2023 --source "Local Government"

  # Show collection info
  visual-rag info --collection my_docs
        """,
    )
    parser.add_argument("--debug", action="store_true", help="Enable debug logging")

    subparsers = parser.add_subparsers(dest="command", help="Command")

    # =========================================================================
    # PROCESS command
    # =========================================================================
    process_parser = subparsers.add_parser(
        "process",
        help="Process PDFs: embed, upload to Cloudinary, index in Qdrant",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    process_parser.add_argument(
        "--reports-dir", type=str, required=True, help="Directory containing PDF files"
    )
    process_parser.add_argument(
        "--metadata-file",
        type=str,
        help="JSON file with filename β†’ metadata mapping (like filename_metadata.json)",
    )
    process_parser.add_argument(
        "--collection", type=str, default="visual_documents", help="Qdrant collection name"
    )
    process_parser.add_argument(
        "--model",
        type=str,
        default="vidore/colSmol-500M",
        help="Model name (vidore/colSmol-500M, vidore/colpali-v1.3, etc.)",
    )
    process_parser.add_argument("--batch-size", type=int, default=8, help="Embedding batch size")
    process_parser.add_argument("--config", type=str, help="Path to config.yaml file")
    process_parser.add_argument(
        "--no-cloudinary", action="store_true", help="Skip Cloudinary uploads"
    )
    process_parser.add_argument(
        "--crop-empty",
        action="store_true",
        help="Crop empty whitespace from page images before embedding (default: off).",
    )
    process_parser.add_argument(
        "--crop-empty-percentage-to-remove",
        type=float,
        default=0.9,
        help="Kept for traceability; currently does not affect cropping behavior (default: 0.9).",
    )
    process_parser.add_argument(
        "--crop-empty-remove-page-number",
        action="store_true",
        help="If set, attempts to crop away the bottom region that contains sparse page numbers (default: off).",
    )
    process_parser.add_argument(
        "--no-skip-existing",
        action="store_true",
        help="Process all pages even if they exist in Qdrant",
    )
    process_parser.add_argument(
        "--force-recreate", action="store_true", help="Delete and recreate collection"
    )
    process_parser.add_argument(
        "--dry-run", action="store_true", help="Show what would be processed without doing it"
    )
    process_parser.add_argument(
        "--strategy",
        type=str,
        default="pooling",
        choices=["pooling", "standard", "all"],
        help="Embedding strategy: 'pooling' (NOVEL), 'standard' (BASELINE), "
        "'all' (embed once, store BOTH for comparison)",
    )
    process_parser.add_argument(
        "--torch-dtype",
        type=str,
        default="auto",
        choices=["auto", "float32", "float16", "bfloat16"],
        help="Torch dtype for model weights (default: auto; CUDA->bfloat16, else float32).",
    )
    process_parser.add_argument(
        "--qdrant-vector-dtype",
        type=str,
        default="float16",
        choices=["float16", "float32"],
        help="Datatype for vectors stored in Qdrant (default: float16).",
    )
    process_parser.add_argument(
        "--processor-speed",
        type=str,
        default="fast",
        choices=["fast", "slow", "auto"],
        help="Processor implementation: fast (default, with fallback to slow), slow, or auto.",
    )
    process_grpc_group = process_parser.add_mutually_exclusive_group()
    process_grpc_group.add_argument(
        "--prefer-grpc",
        dest="prefer_grpc",
        action="store_true",
        default=True,
        help="Use gRPC for Qdrant client (recommended).",
    )
    process_grpc_group.add_argument(
        "--no-prefer-grpc",
        dest="prefer_grpc",
        action="store_false",
        help="Disable gRPC for Qdrant client.",
    )
    process_parser.set_defaults(func=cmd_process)

    # =========================================================================
    # SEARCH command
    # =========================================================================
    search_parser = subparsers.add_parser(
        "search",
        help="Search documents",
    )
    search_parser.add_argument("--query", type=str, required=True, help="Search query")
    search_parser.add_argument(
        "--collection", type=str, default="visual_documents", help="Qdrant collection name"
    )
    search_parser.add_argument(
        "--model", type=str, default="vidore/colSmol-500M", help="Model name"
    )
    search_parser.add_argument(
        "--processor-speed",
        type=str,
        default="fast",
        choices=["fast", "slow", "auto"],
        help="Processor implementation: fast (default, with fallback to slow), slow, or auto.",
    )
    search_parser.add_argument("--top-k", type=int, default=10, help="Number of results")
    search_parser.add_argument(
        "--strategy",
        type=str,
        default="single_full",
        choices=["single_full", "single_tiles", "single_global", "two_stage"],
        help="Search strategy",
    )
    search_parser.add_argument(
        "--prefetch-k", type=int, default=200, help="Prefetch candidates for two-stage retrieval"
    )
    search_parser.add_argument(
        "--stage1-mode",
        type=str,
        default="pooled_query_vs_tiles",
        choices=["pooled_query_vs_tiles", "tokens_vs_tiles", "pooled_query_vs_global"],
        help="Stage 1 mode for two-stage retrieval",
    )
    search_parser.add_argument("--year", type=int, help="Filter by year")
    search_parser.add_argument("--source", type=str, help="Filter by source")
    search_parser.add_argument("--district", type=str, help="Filter by district")
    search_parser.add_argument(
        "--show-text", action="store_true", help="Show text snippets in results"
    )
    search_grpc_group = search_parser.add_mutually_exclusive_group()
    search_grpc_group.add_argument(
        "--prefer-grpc",
        dest="prefer_grpc",
        action="store_true",
        default=True,
        help="Use gRPC for Qdrant client (recommended).",
    )
    search_grpc_group.add_argument(
        "--no-prefer-grpc",
        dest="prefer_grpc",
        action="store_false",
        help="Disable gRPC for Qdrant client.",
    )
    search_parser.set_defaults(func=cmd_search)

    # =========================================================================
    # INFO command
    # =========================================================================
    info_parser = subparsers.add_parser(
        "info",
        help="Show collection info",
    )
    info_parser.add_argument(
        "--collection", type=str, default="visual_documents", help="Qdrant collection name"
    )
    info_grpc_group = info_parser.add_mutually_exclusive_group()
    info_grpc_group.add_argument(
        "--prefer-grpc",
        dest="prefer_grpc",
        action="store_true",
        default=True,
        help="Use gRPC for Qdrant client (recommended).",
    )
    info_grpc_group.add_argument(
        "--no-prefer-grpc",
        dest="prefer_grpc",
        action="store_false",
        help="Disable gRPC for Qdrant client.",
    )
    info_parser.set_defaults(func=cmd_info)

    # Parse and execute
    args = parser.parse_args()

    setup_logging(args.debug)

    if not args.command:
        parser.print_help()
        sys.exit(0)

    args.func(args)


if __name__ == "__main__":
    main()