-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathupload.sh
More file actions
executable file
·2278 lines (1967 loc) · 84.6 KB
/
upload.sh
File metadata and controls
executable file
·2278 lines (1967 loc) · 84.6 KB
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# Script to upload files to ChromaDB with store-specific optimizations
# Supports PDFs (with OCR), source code (with AST chunking), and markdown
# Works with both persistence (local) and remote ChromaDB clients
#
# Usage: ./upload_new_pdfs.sh [OPTIONS]
#
# Options:
# -c, --collection NAME ChromaDB collection name (default: ResearchLibrary)
# -h, --host HOST ChromaDB host for remote client (default: localhost)
# -p, --port PORT ChromaDB port for remote client (default: 9000)
# -l, --limit NUMBER Maximum number of files to upload (optional)
# -i, --input-path PATH Path to recursively search for files (required)"
# -d, --data-path PATH Path for ChromaDB persistence data storage (forces persistence mode)
# -e, --embedding-model MODEL Embedding model (stella|modernbert|bge-large|default) [default: stella]
# --store TYPE Store type: pdf, source-code, markdown [default: pdf]
# --chunk-size TOKENS Chunk size in tokens (auto=model-specific, or custom number)
# --chunk-overlap TOKENS Chunk overlap in tokens (auto=model-specific, or custom number)
# --batch-size NUMBER Upload batch size to avoid payload limits (default: 50)
# --delete-collection Delete and recreate the collection before upload
# --delete-project NAME Delete specific git project from collection
# --delete-failed-project Auto-delete project if any upload fails
# --dry-run Preview chunk sizes without uploading
# --disable-ocr Disable OCR for image PDFs (OCR enabled by default)
# --ocr-engine ENGINE OCR engine: tesseract, easyocr (default: tesseract)
# --ocr-language LANG OCR language code (default: eng)
# --help Show this help message
#
# Path Types:
# --input-path: Directory containing files to index (searched recursively by store type)
# --data-path: Directory where ChromaDB stores its database files (persistence mode only)
#
# Client Selection:
# - If --data-path is specified: uses PersistentClient
# - Otherwise: uses HttpClient with --host and --port (default: localhost:9000)
#
# Environment variables:
# PDF_INPUT_PATH: Path to directory containing files (alternative to -i option)
# CHROMA_DATA_PATH: Default path for persistence client data directory
set -e
# Default values
COLLECTION_NAME="ResearchLibrary"
CHROMA_HOST="localhost"
CHROMA_PORT="9000"
UPLOAD_LIMIT=""
INPUT_PATH="${PDF_INPUT_PATH:-}" # Use environment variable or require CLI option
CHROMA_DATA_DIR=""
CLIENT_TYPE="remote"
EMBEDDING_MODEL="stella"
CHUNK_SIZE="auto"
CHUNK_OVERLAP="auto"
BATCH_SIZE="50"
DELETE_COLLECTION="false"
DELETE_PROJECT=""
DELETE_FAILED_PROJECT="false"
DRY_RUN="false"
OCR_ENABLED="true"
OCR_ENGINE="tesseract"
OCR_LANGUAGE="eng"
STORE_TYPE="pdf"
GIT_DEPTH=""
# Function to show help
show_help() {
echo "Usage: $0 [OPTIONS]"
echo ""
echo "Options:"
echo " -c, --collection NAME ChromaDB collection name (default: ResearchLibrary)"
echo " -h, --host HOST ChromaDB host for remote client (default: localhost)"
echo " -p, --port PORT ChromaDB port for remote client (default: 9000)"
echo " -l, --limit NUMBER Maximum number of files to upload (optional)"
echo " -i, --input-path PATH Path to recursively search for PDF files (required)"
echo " -d, --data-path PATH Path for ChromaDB persistence data storage (forces persistence mode)"
echo " -e, --embedding-model MODEL Embedding model: stella, modernbert, bge-large, default [default: stella]"
echo " --store TYPE Store type: pdf, source-code, markdown [default: pdf]"
echo " --chunk-size TOKENS Chunk size in tokens (auto=model-optimized, or specify number)"
echo " --chunk-overlap TOKENS Chunk overlap in tokens (auto=model-optimized, or specify number)"
echo " --batch-size NUMBER Upload batch size to avoid payload limits (default: 50)"
echo " --depth LEVELS Git project search depth (1=direct subdirs only, default: unlimited)"
echo " --delete-collection Delete and recreate the collection before upload"
echo " --delete-project NAME Delete specific git project from collection"
echo " --delete-failed-project Auto-delete project if any upload fails"
echo " --dry-run Preview chunk sizes without uploading"
echo " --disable-ocr Disable OCR for image PDFs (OCR enabled by default)"
echo " --ocr-engine ENGINE OCR engine: tesseract, easyocr (default: tesseract)"
echo " --ocr-language LANG OCR language code (default: eng)"
echo " --help Show this help message"
echo ""
echo "Path Types:"
echo " --input-path: Directory containing PDF files to index (searched recursively)"
echo " --data-path: Directory where ChromaDB stores its database files (persistence mode only)"
echo ""
echo "Client Selection:"
echo " - If --data-path is specified: uses PersistentClient"
echo " - Otherwise: uses HttpClient with --host and --port (default: localhost:9000)"
echo ""
echo "Environment variables:"
echo " PDF_INPUT_PATH: Path to directory containing PDF files (alternative to -i option)"
echo " CHROMA_DATA_PATH: Default path for persistence client data directory"
echo ""
echo "Embedding Models:"
echo " stella - Stella-400m (Top MTEB performer, 1024 dims)"
echo " modernbert - ModernBERT-large (Latest state-of-the-art, 1024 dims)"
echo " bge-large - BGE-Large (Production proven, 1024 dims)"
echo " default - SentenceTransformers default (all-MiniLM-L6-v2, 384 dims)"
echo ""
echo "Examples:"
echo " # Upload PDFs (default)"
echo " $0 -i /path/to/pdfs -c MyCollection -e stella"
echo ""
echo " # Upload source code with AST-aware chunking"
echo " $0 -i /path/to/source --store source-code -c CodeLibrary -e stella"
echo ""
echo " # Upload markdown documentation files"
echo " $0 -i /path/to/docs --store markdown -c DocsLibrary -e stella"
echo ""
echo " # Advanced options - custom chunk size"
echo " $0 -i /path/to/files --store pdf --delete-collection -c MyCollection -e stella --chunk-size 400"
echo ""
echo " # Model-optimized chunking (recommended)"
echo " $0 -i /path/to/files --store pdf -c MyCollection -e stella # Uses optimal 460 tokens for Stella"
echo ""
echo " # Handling large files (if you get payload size errors)"
echo " $0 -i /path/to/source --store source-code --batch-size 25 --chunk-size 1000"
echo ""
echo " # Project cleanup and recovery"
echo " $0 --delete-project my-project-name # Delete specific project"
echo " $0 -i /path/to/source --store source-code --delete-failed-project # Auto-cleanup on failure"
echo ""
echo " # Preview and optimize settings"
echo " $0 -i /path/to/source --store source-code --dry-run # Preview chunk sizes"
}
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
-c|--collection)
COLLECTION_NAME="$2"
shift 2
;;
-h|--host)
CHROMA_HOST="$2"
shift 2
;;
-p|--port)
CHROMA_PORT="$2"
shift 2
;;
-l|--limit)
UPLOAD_LIMIT="$2"
shift 2
;;
-i|--input-path)
INPUT_PATH="$2"
shift 2
;;
-d|--data-path)
CHROMA_DATA_DIR="$2"
CLIENT_TYPE="persistence"
shift 2
;;
-e|--embedding-model)
EMBEDDING_MODEL="$2"
shift 2
;;
--store)
STORE_TYPE="$2"
shift 2
;;
--chunk-size)
CHUNK_SIZE="$2"
shift 2
;;
--chunk-overlap)
CHUNK_OVERLAP="$2"
shift 2
;;
--batch-size)
BATCH_SIZE="$2"
shift 2
;;
--delete-collection)
DELETE_COLLECTION="true"
shift
;;
--delete-project)
DELETE_PROJECT="$2"
shift 2
;;
--delete-failed-project)
DELETE_FAILED_PROJECT="true"
shift
;;
--dry-run)
DRY_RUN="true"
shift
;;
--disable-ocr)
OCR_ENABLED="false"
shift
;;
--ocr-engine)
OCR_ENGINE="$2"
shift 2
;;
--ocr-language)
OCR_LANGUAGE="$2"
shift 2
;;
--depth)
GIT_DEPTH="$2"
shift 2
;;
--help)
show_help
exit 0
;;
*)
echo "Unknown option: $1"
echo "Use --help for usage information"
exit 1
;;
esac
done
# Set default data directory if using persistence mode but no path specified
if [ "$CLIENT_TYPE" = "persistence" ] && [ -z "$CHROMA_DATA_DIR" ]; then
CHROMA_DATA_DIR="${CHROMA_DATA_PATH:-./chroma_data_${COLLECTION_NAME}}"
fi
# Validate embedding model
case "$EMBEDDING_MODEL" in
stella|modernbert|bge-large|default)
;;
*)
echo "❌ Invalid embedding model: $EMBEDDING_MODEL"
echo "Valid options: stella, modernbert, bge-large, default"
echo "Use --help for more information"
exit 1
;;
esac
# Validate OCR engine
case "$OCR_ENGINE" in
tesseract|easyocr)
;;
*)
echo "❌ Invalid OCR engine: $OCR_ENGINE"
echo "Valid options: tesseract, easyocr"
echo "Use --help for more information"
exit 1
;;
esac
# Validate depth parameter
if [ -n "$GIT_DEPTH" ]; then
# Check if depth is a positive integer
if ! [[ "$GIT_DEPTH" =~ ^[0-9]+$ ]] || [ "$GIT_DEPTH" -lt 1 ]; then
echo "❌ Invalid depth value: $GIT_DEPTH"
echo "Depth must be a positive integer (1 or higher)"
echo "Use --help for more information"
exit 1
fi
fi
# Set model-specific defaults with 10% safety margin for query context
set_model_defaults() {
local model="$1"
local store="$2"
case "$model" in
stella)
# Stella: 512 token limit, 10% safety margin = 460 tokens
MODEL_CHUNK_SIZE="460"
MODEL_CHUNK_OVERLAP="46" # 10% overlap
;;
modernbert)
# ModernBERT: 8192 token limit, use conservative 1024 with 10% margin = 920 tokens
MODEL_CHUNK_SIZE="920"
MODEL_CHUNK_OVERLAP="92" # 10% overlap
;;
bge-large)
# BGE-Large: ~512 token limit (BERT-based), 10% safety margin = 460 tokens
MODEL_CHUNK_SIZE="460"
MODEL_CHUNK_OVERLAP="46" # 10% overlap
;;
default)
# Default SentenceTransformers: all-MiniLM-L6-v2, ~512 tokens
MODEL_CHUNK_SIZE="460"
MODEL_CHUNK_OVERLAP="46" # 10% overlap
;;
*)
echo "❌ Unknown model for chunk size calculation: $model"
exit 1
;;
esac
# Apply store-specific adjustments if needed
case "$store" in
source-code)
# Source code benefits from slightly smaller chunks for better AST parsing
MODEL_CHUNK_SIZE="$((MODEL_CHUNK_SIZE - 60))"
MODEL_CHUNK_OVERLAP="$((MODEL_CHUNK_OVERLAP / 2))"
;;
markdown)
# Markdown can use slightly smaller chunks for better semantic coherence
# Extra reduction for heading context preservation
MODEL_CHUNK_SIZE="$((MODEL_CHUNK_SIZE - 30))"
;;
pdf)
# PDFs use default model settings
;;
esac
}
# Set chunk sizes based on embedding model if auto
if [ "$CHUNK_SIZE" = "auto" ]; then
set_model_defaults "$EMBEDDING_MODEL" "$STORE_TYPE"
CHUNK_SIZE="$MODEL_CHUNK_SIZE"
CHUNK_OVERLAP="$MODEL_CHUNK_OVERLAP"
fi
# Validate store type and apply other defaults
case "$STORE_TYPE" in
pdf)
# PDF settings
;;
source-code)
# Disable OCR for source code by default
if [ "$OCR_ENABLED" = "true" ]; then
OCR_ENABLED="false"
fi
;;
markdown)
# Disable OCR for markdown by default
if [ "$OCR_ENABLED" = "true" ]; then
OCR_ENABLED="false"
fi
;;
*)
echo "❌ Invalid store type: $STORE_TYPE"
echo "Valid options: pdf, source-code, markdown"
echo "Use --help for more information"
exit 1
;;
esac
# Validate chunk sizes are reasonable
if [ "$CHUNK_SIZE" -gt 1000 ]; then
echo "⚠️ Warning: Chunk size $CHUNK_SIZE tokens is quite large"
echo " This may exceed optimal embedding model limits"
echo " Consider using model-specific defaults with --chunk-size auto"
fi
# Function to get file extensions based on store type
get_file_extensions() {
case "$STORE_TYPE" in
pdf)
echo "*.pdf"
;;
source-code)
echo "*.py *.java *.js *.ts *.tsx *.jsx *.go *.rs *.cpp *.c *.cs *.php *.rb *.kt *.scala *.swift"
;;
markdown)
echo "*.md *.txt *.rst *.adoc *.html *.xml"
;;
esac
}
# Function to find git project roots in a directory
find_git_projects() {
local input_path="$1"
local output_file="$2"
local depth="$3" # Optional depth parameter
# Clear output file
> "$output_file"
# Build find command with optional maxdepth
local find_cmd="find \"$input_path\""
if [ -n "$depth" ]; then
# For depth=1, we want maxdepth=2 (input_path + 1 level down for .git directories)
local max_depth=$((depth + 1))
find_cmd="$find_cmd -maxdepth $max_depth"
fi
find_cmd="$find_cmd -name \".git\" -type d"
# Execute the find command and process results
eval "$find_cmd" | while read -r git_dir; do
project_root=$(dirname "$git_dir")
echo "$project_root" >> "$output_file"
done
# Remove duplicates and sort
if [ -f "$output_file" ]; then
sort -u "$output_file" -o "$output_file"
fi
}
# Function to get git metadata for a project
get_git_metadata() {
local project_root="$1"
local metadata_file="$2"
if [ ! -d "$project_root/.git" ]; then
echo "ERROR: Not a git repository: $project_root" >&2
return 1
fi
cd "$project_root" || return 1
# Get git metadata
local commit_hash=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
local remote_url=$(git remote get-url origin 2>/dev/null || echo "unknown")
local branch=$(git branch --show-current 2>/dev/null || echo "unknown")
local project_name=$(basename "$project_root")
# Write metadata to file
cat > "$metadata_file" << EOF
GIT_PROJECT_ROOT="$project_root"
GIT_COMMIT_HASH="$commit_hash"
GIT_REMOTE_URL="$remote_url"
GIT_BRANCH="$branch"
GIT_PROJECT_NAME="$project_name"
EOF
cd - > /dev/null
return 0
}
# Function to find files based on store type
find_files() {
local input_path="$1"
local output_file="$2"
local extensions=$(get_file_extensions)
# Clear output file
> "$output_file"
if [ "$STORE_TYPE" = "source-code" ]; then
# For source code, use git-aware file discovery
local git_projects_file="/tmp/git_projects_$$.txt"
find_git_projects "$input_path" "$git_projects_file" "$GIT_DEPTH"
if [ -s "$git_projects_file" ]; then
# Process each git project
while IFS= read -r project_root; do
echo " Found git project: $project_root"
# Get files from git ls-files (respects .gitignore)
cd "$project_root" || continue
# Use git ls-files and filter by extensions
for ext in $extensions; do
# Convert shell glob to git pathspec pattern
git_pattern=$(echo "$ext" | sed 's/\*//') # Remove leading *
git ls-files "*$git_pattern" 2>/dev/null >> "$output_file" || true
done
cd - > /dev/null
done < "$git_projects_file"
# Convert relative paths to absolute paths
local temp_file="/tmp/absolute_paths_$$.txt"
> "$temp_file"
while IFS= read -r relative_path; do
# Find which project this file belongs to
while IFS= read -r project_root; do
if [ -f "$project_root/$relative_path" ]; then
echo "$project_root/$relative_path" >> "$temp_file"
break
fi
done < "$git_projects_file"
done < "$output_file"
mv "$temp_file" "$output_file"
else
echo " No git projects found, falling back to regular file search"
# Fall back to regular find for non-git directories
for ext in $extensions; do
find "$input_path" -name "$ext" -type f >> "$output_file" 2>/dev/null || true
done
fi
rm -f "$git_projects_file"
else
# For PDF and markdown, use regular find
# Use proper quoting to prevent glob expansion
while IFS= read -r ext; do
find "$input_path" -name "$ext" -type f >> "$output_file" 2>/dev/null || true
done < <(echo "$extensions" | tr ' ' '\n')
fi
}
# Validate that input path is provided (unless doing project deletion only)
if [ -z "$INPUT_PATH" ] && [ -z "$DELETE_PROJECT" ]; then
echo "❌ Error: Input path is required"
echo ""
echo "Please specify the PDF input path using one of these methods:"
echo " 1. CLI option: $0 -i /path/to/pdfs"
echo " 2. Environment variable: PDF_INPUT_PATH=/path/to/pdfs $0"
echo ""
echo "Use --help for more information"
exit 1
fi
LOG_FILE="/tmp/upload_new_log_$(date +%Y%m%d_%H%M%S).txt"
MAX_PARALLEL_JOBS=$(sysctl -n hw.ncpu) # Use number of CPU cores
# Validate input path exists (unless doing project deletion only)
if [ -n "$INPUT_PATH" ] && [ ! -d "$INPUT_PATH" ]; then
echo "❌ Input path does not exist: $INPUT_PATH"
exit 1
fi
# Skip main intro for project deletion mode
if [ -z "$DELETE_PROJECT" ]; then
echo "Starting SMART PDF upload to ChromaDB with Enhanced Embeddings"
echo "Collection: $COLLECTION_NAME"
echo "Input path: $INPUT_PATH"
else
echo "ChromaDB Project Management"
echo "Collection: $COLLECTION_NAME"
fi
echo "Client type: $CLIENT_TYPE"
if [ "$CLIENT_TYPE" = "remote" ]; then
echo "ChromaDB: $CHROMA_HOST:$CHROMA_PORT"
else
echo "Data directory: $CHROMA_DATA_DIR"
fi
echo "Embedding model: $EMBEDDING_MODEL"
case "$EMBEDDING_MODEL" in
stella)
echo " → Stella-400m (1024 dims, Top MTEB performer)"
;;
modernbert)
echo " → ModernBERT-large (1024 dims, Latest state-of-the-art)"
;;
bge-large)
echo " → BGE-Large (1024 dims, Production proven)"
;;
default)
echo " → SentenceTransformers default (384 dims, all-MiniLM-L6-v2)"
;;
esac
echo "Chunk size: $CHUNK_SIZE tokens (model-optimized for $EMBEDDING_MODEL)"
echo "Chunk overlap: $CHUNK_OVERLAP tokens"
if [ "$STORE_TYPE" = "source-code" ]; then
if [ -n "$GIT_DEPTH" ]; then
echo "Git project search depth: $GIT_DEPTH levels"
else
echo "Git project search depth: unlimited"
fi
fi
echo "OCR enabled: $OCR_ENABLED"
if [ "$OCR_ENABLED" = "true" ]; then
echo " → OCR engine: $OCR_ENGINE"
echo " → OCR language: $OCR_LANGUAGE"
fi
if [ "$DELETE_COLLECTION" = "true" ]; then
echo "⚠ Collection will be deleted and recreated"
fi
echo "Parallel jobs: $MAX_PARALLEL_JOBS (CPU cores)"
if [ -n "$UPLOAD_LIMIT" ]; then
echo "Upload limit: $UPLOAD_LIMIT files"
fi
echo "Log file: $LOG_FILE"
# Check if required Python packages are available (simplified for server-side embeddings)
echo "Checking Python dependencies..."
python3 -c "
try:
import chromadb
import fitz # pymupdf
import PIL # Pillow
import packaging.version
print('✓ Core packages available')
print(f' chromadb version: {chromadb.__version__}')
print(f' pymupdf version: {fitz.version[0]}')
print(f' pillow version: {PIL.__version__}')
# Verify ChromaDB version compatibility
min_version = '1.0.0'
if packaging.version.parse(chromadb.__version__) < packaging.version.parse(min_version):
print(f'⚠ Warning: ChromaDB version {chromadb.__version__} may not be compatible')
print(f' Recommended: pip install --upgrade chromadb')
else:
print(f'✓ ChromaDB version {chromadb.__version__} is compatible')
# Check OCR dependencies if enabled
ocr_enabled = '$OCR_ENABLED' == 'true'
ocr_engine = '$OCR_ENGINE'
if ocr_enabled:
ocr_available = False
if ocr_engine == 'tesseract':
try:
import pytesseract
# Test tesseract binary
version = pytesseract.get_tesseract_version()
print(f'✓ Tesseract OCR available (version: {version})')
ocr_available = True
except Exception as e:
print(f'❌ Tesseract OCR not available: {e}')
print(' System dependency required. Install with:')
print(' macOS: brew install tesseract')
print(' Ubuntu/Debian: sudo apt-get install tesseract-ocr')
print(' CentOS/RHEL: sudo yum install tesseract')
print(' Or use EasyOCR (no system deps): pip install .[easyocr] --ocr-engine easyocr')
print(' Or disable OCR with: --disable-ocr')
elif ocr_engine == 'easyocr':
try:
import easyocr
print('✓ EasyOCR available (pure Python, no system dependencies)')
ocr_available = True
except ImportError:
print('❌ EasyOCR not available')
print(' Install with: pip install .[easyocr]')
print(' Or use tesseract: --ocr-engine tesseract')
print(' Or disable OCR with: --disable-ocr')
if not ocr_available:
print('❌ OCR dependencies not met - exiting')
print(' Fix dependencies or use --disable-ocr flag')
exit(1)
else:
print(f'ℹ️ OCR enabled with {ocr_engine} engine')
else:
print('ℹ️ OCR disabled - image PDFs will be skipped')
# Note about server-side embeddings
print('ℹ️ Using server-side embeddings - no local ML models required')
except ImportError as e:
print(f'✗ Missing package: {e}')
print('Install dependencies with: pip install .')
exit(1)
" 2>&1 | tee -a "$LOG_FILE"
if [ $? -ne 0 ]; then
echo "Please install required packages: pip install ."
exit 1
fi
# Test ChromaDB connection
echo ""
echo "Testing ChromaDB connection..."
if [ "$CLIENT_TYPE" = "remote" ]; then
if ! curl -s "$CHROMA_HOST:$CHROMA_PORT/api/v2/heartbeat" > /dev/null 2>&1; then
echo "❌ Cannot connect to ChromaDB at $CHROMA_HOST:$CHROMA_PORT"
if [ "$CHROMA_HOST" = "localhost" ]; then
echo "💡 Run: ./setup_local_chroma.sh $COLLECTION_NAME"
fi
exit 1
fi
echo "✅ ChromaDB is running"
else
echo "✅ Using persistence client (data path: $CHROMA_DATA_DIR)"
# Create data directory if it doesn't exist
mkdir -p "$CHROMA_DATA_DIR"
fi
# Handle project deletion if requested
if [ -n "$DELETE_PROJECT" ]; then
echo ""
echo "🗑️ Deleting project '$DELETE_PROJECT' from collection '$COLLECTION_NAME'..."
python3 -c "
import chromadb
import sys
try:
if '$CLIENT_TYPE' == 'remote':
client = chromadb.HttpClient(host='$CHROMA_HOST', port=$CHROMA_PORT)
else:
client = chromadb.PersistentClient(path='$CHROMA_DATA_DIR')
try:
collection = client.get_collection('$COLLECTION_NAME')
print(f'Found collection: {collection.name}')
# Query for documents from this project (try by project name first)
existing_docs = collection.get(
where={'git_project_name': '$DELETE_PROJECT'},
include=['metadatas'],
limit=10 # Just need to check if project exists
)
# If not found by name, try by project root path containing the name
if not existing_docs['ids']:
all_docs = collection.get(include=['metadatas'], limit=1000)
matching_ids = []
for i, metadata in enumerate(all_docs['metadatas']):
if metadata and 'git_project_root' in metadata:
if '$DELETE_PROJECT' in metadata['git_project_root']:
matching_ids.append(all_docs['ids'][i])
if matching_ids:
existing_docs = {'ids': matching_ids[:10], 'metadatas': [all_docs['metadatas'][all_docs['ids'].index(id)] for id in matching_ids[:10]]}
if not existing_docs['ids']:
print(f'⚠️ Project \"$DELETE_PROJECT\" not found in collection')
print('Available projects:')
# Get sample of all projects
all_docs = collection.get(include=['metadatas'], limit=100)
projects = set()
for metadata in all_docs['metadatas']:
if metadata and 'git_project_name' in metadata:
projects.add(metadata['git_project_name'])
if projects:
for project in sorted(projects):
print(f' - {project}')
else:
print(' (No git projects found)')
sys.exit(1)
print(f'Found project \"$DELETE_PROJECT\" - deleting all chunks...')
# Get all document IDs for this project in batches
all_project_ids = []
batch_size = 1000
offset = 0
while True:
# Get documents by project name
batch = collection.get(
where={'git_project_name': '$DELETE_PROJECT'},
include=['metadatas'],
limit=batch_size,
offset=offset
)
# If no more by name, try by project root path
if not batch['ids'] and offset == 0:
all_docs = collection.get(include=['metadatas'], limit=10000)
matching_ids = []
for i, metadata in enumerate(all_docs['metadatas']):
if metadata and 'git_project_root' in metadata:
if '$DELETE_PROJECT' in metadata['git_project_root']:
matching_ids.append(all_docs['ids'][i])
# Create batch structure from matching IDs
if matching_ids:
batch_ids = matching_ids[offset:offset+batch_size]
batch = {'ids': batch_ids, 'metadatas': [all_docs['metadatas'][all_docs['ids'].index(id)] for id in batch_ids]}
if not batch['ids']:
break
all_project_ids.extend(batch['ids'])
offset += batch_size
if len(batch['ids']) < batch_size:
break
if all_project_ids:
# Delete in batches (ChromaDB delete has limits)
delete_batch_size = 100
deleted_count = 0
for i in range(0, len(all_project_ids), delete_batch_size):
batch_ids = all_project_ids[i:i+delete_batch_size]
collection.delete(ids=batch_ids)
deleted_count += len(batch_ids)
print(f'✅ Deleted {deleted_count} chunks from project \"$DELETE_PROJECT\"')
else:
print('⚠️ No chunks found to delete')
except Exception as e:
if 'does not exist' in str(e):
print(f'❌ Collection \"$COLLECTION_NAME\" does not exist')
else:
print(f'❌ Error accessing collection: {e}')
sys.exit(1)
except Exception as e:
print(f'❌ Error connecting to ChromaDB: {e}')
sys.exit(1)
" 2>&1 | tee -a "$LOG_FILE"
if [ $? -eq 0 ]; then
echo "✅ Project deletion completed successfully"
echo "You can now re-run the upload command to re-index the project"
exit 0
else
echo "❌ Project deletion failed"
exit 1
fi
fi
# Handle collection deletion if requested
if [ "$DELETE_COLLECTION" = "true" ]; then
echo ""
echo "🗑️ Deleting existing collection '$COLLECTION_NAME'..."
python3 -c "
import chromadb
import sys
try:
if '$CLIENT_TYPE' == 'remote':
client = chromadb.HttpClient(host='$CHROMA_HOST', port=$CHROMA_PORT)
else:
client = chromadb.PersistentClient(path='$CHROMA_DATA_DIR')
try:
client.delete_collection('$COLLECTION_NAME')
print('✅ Collection \"$COLLECTION_NAME\" deleted successfully')
except Exception as e:
if 'does not exist' in str(e).lower():
print('ℹ️ Collection \"$COLLECTION_NAME\" did not exist')
else:
print(f'⚠️ Error deleting collection: {e}')
# Create new empty collection with specified embedding model
try:
# For server-side embeddings, we don't specify embedding function here
# The server will handle embedding based on its configuration
collection = client.create_collection('$COLLECTION_NAME')
print(f'✅ Created new empty collection: {collection.name}')
print(f'Server will use embedding model: $EMBEDDING_MODEL')
except Exception as e:
print(f'❌ Error creating collection: {e}')
sys.exit(1)
except Exception as e:
print(f'❌ Error connecting to ChromaDB: {e}')
sys.exit(1)
" 2>&1 | tee -a "$LOG_FILE"
if [ $? -ne 0 ]; then
echo "❌ Failed to delete/recreate collection"
exit 1
fi
fi
# Handle git project change detection for source-code
if [ "$STORE_TYPE" = "source-code" ]; then
echo ""
echo "Checking for git project changes..."
# Find git projects in input path
GIT_PROJECTS_FILE="/tmp/git_projects_${COLLECTION_NAME}_$(date +%s).txt"
find_git_projects "$INPUT_PATH" "$GIT_PROJECTS_FILE" "$GIT_DEPTH"
if [ -s "$GIT_PROJECTS_FILE" ]; then
# Check each git project for changes
while IFS= read -r project_root; do
project_name=$(basename "$project_root")
echo "Checking git project: $project_name"
# Get current git metadata
GIT_METADATA_FILE="/tmp/git_metadata_${project_name}_$(date +%s).txt"
if get_git_metadata "$project_root" "$GIT_METADATA_FILE"; then
source "$GIT_METADATA_FILE"
# Check if project exists in ChromaDB and compare commit hash
python3 -c "
import chromadb
import sys
try:
if '$CLIENT_TYPE' == 'remote':
client = chromadb.HttpClient(host='$CHROMA_HOST', port=$CHROMA_PORT)
else:
client = chromadb.PersistentClient(path='$CHROMA_DATA_DIR')
try:
collection = client.get_collection('$COLLECTION_NAME')
# Query for documents from this project
existing_docs = collection.get(
where={'git_project_root': '$GIT_PROJECT_ROOT'},
include=['metadatas'],
limit=10 # Just need to check a few to get the commit hash
)
if existing_docs['ids']:
stored_commit = existing_docs['metadatas'][0].get('git_commit_hash', 'unknown')
current_commit = '$GIT_COMMIT_HASH'
print(f' Stored commit: {stored_commit[:12] if stored_commit != \"unknown\" else \"unknown\"}')
print(f' Current commit: {current_commit[:12]}')
if stored_commit != current_commit:
print(' 🔄 Project has changed, deleting existing chunks...')
# Delete all chunks for this project
# Get all document IDs for this project in batches
all_project_ids = []
batch_size = 1000
offset = 0
while True:
batch = collection.get(
where={'git_project_root': '$GIT_PROJECT_ROOT'},
include=['metadatas'],
limit=batch_size,
offset=offset
)
if not batch['ids']:
break
all_project_ids.extend(batch['ids'])
offset += batch_size
if len(batch['ids']) < batch_size:
break
if all_project_ids:
# Delete in batches (ChromaDB delete has limits)
delete_batch_size = 100
deleted_count = 0
for i in range(0, len(all_project_ids), delete_batch_size):
batch_ids = all_project_ids[i:i+delete_batch_size]
collection.delete(ids=batch_ids)
deleted_count += len(batch_ids)
print(f' ✅ Deleted {deleted_count} existing chunks')
sys.exit(10) # Signal that project was deleted
else:
print(' ⚠️ No chunks found to delete')
sys.exit(11) # Signal no chunks to delete
else:
print(' ✓ Project unchanged, will check individual files')
sys.exit(0) # Normal processing
else:
print(' 📥 New project, will index all files')
sys.exit(0) # Normal processing
except Exception as e:
if 'does not exist' in str(e):
print(' 📥 Collection does not exist, will create and index all files')
sys.exit(0)
else:
print(f'Error querying collection: {e}')
sys.exit(1)
except Exception as e:
print(f'Error connecting to ChromaDB: {e}')
sys.exit(1)
"
check_result=$?
if [ $check_result -eq 10 ]; then
echo " Project $project_name was updated and old chunks deleted"
elif [ $check_result -eq 11 ]; then
echo " Project $project_name had no existing chunks"
elif [ $check_result -eq 0 ]; then
echo " Project $project_name processing normally"
else
echo " Error checking project $project_name"
fi
rm -f "$GIT_METADATA_FILE"
else
echo " ⚠️ Could not get git metadata for $project_root"
fi
done < "$GIT_PROJECTS_FILE"
rm -f "$GIT_PROJECTS_FILE"
else
echo "No git projects found in input path"
fi
fi
# Query ChromaDB for existing files
echo ""
echo "Querying ChromaDB for existing files..."
EXISTING_FILES_LIST="/tmp/existing_files_${COLLECTION_NAME}_$(date +%s).txt"
python3 -c "
import chromadb
import sys
try:
# Use appropriate client based on CLIENT_TYPE
if '$CLIENT_TYPE' == 'remote':
client = chromadb.HttpClient(host='$CHROMA_HOST', port=$CHROMA_PORT)
print('✓ Connected to ChromaDB using HttpClient')
else:
client = chromadb.PersistentClient(path='$CHROMA_DATA_DIR')
print('✓ Connected to ChromaDB using PersistentClient')
# Set embedding model info for server communication
embedding_model = '$EMBEDDING_MODEL'
print(f'Using embedding model: {embedding_model}')
try: