-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrag_pipeline.py
More file actions
2237 lines (1857 loc) · 89.8 KB
/
Copy pathrag_pipeline.py
File metadata and controls
2237 lines (1857 loc) · 89.8 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 python3
"""
Local RAG Pipeline with Git Commit Support and LaTeX-Aware Processing
A comprehensive RAG pipeline for ingesting and querying documents and Git commits locally
"""
import argparse
import hashlib
import os
import shutil
import sqlite3
import subprocess
import sys
import traceback
import re
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Any, Tuple
import uuid
# Load environment variables
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
# dotenv is optional, continue without it
pass
# Core dependencies
import chromadb
from chromadb.config import Settings
import tiktoken
from sentence_transformers import SentenceTransformer
# Optional dependencies
try:
from anthropic import Anthropic
ANTHROPIC_AVAILABLE = True
except ImportError:
ANTHROPIC_AVAILABLE = False
print("Warning: anthropic package not installed. Run: pip install anthropic")
try:
import openai
OPENAI_AVAILABLE = True
except ImportError:
OPENAI_AVAILABLE = False
print("Warning: openai package not installed. Run: pip install openai")
# Configuration from environment variables
class Config:
# Data storage
DATA_DIR = os.getenv('RAG_DATA_DIR', './rag_data')
DATABASE_NAME = os.getenv('RAG_DATABASE_NAME', 'metadata.db')
VECTOR_STORE_DIR = os.getenv('RAG_VECTOR_STORE_DIR', 'chroma_db')
REPOS_DIR = os.getenv('RAG_REPOS_DIR', 'repos')
# AI Models
EMBEDDING_MODEL = os.getenv('RAG_EMBEDDING_MODEL', 'all-MiniLM-L6-v2')
CLAUDE_MODEL = os.getenv('RAG_CLAUDE_MODEL', 'claude-3-sonnet-20240229')
OPENAI_MODEL = os.getenv('RAG_OPENAI_MODEL', 'gpt-3.5-turbo')
DEFAULT_AI_MODEL = os.getenv('RAG_DEFAULT_AI_MODEL', 'claude')
AI_MAX_TOKENS = int(os.getenv('RAG_AI_MAX_TOKENS', '1000'))
# Document processing
CHUNK_SIZE = int(os.getenv('RAG_CHUNK_SIZE', '1000'))
CHUNK_OVERLAP = int(os.getenv('RAG_CHUNK_OVERLAP', '200'))
LATEX_CHUNK_SIZE = int(os.getenv('RAG_LATEX_CHUNK_SIZE', '2000'))
LATEX_CHUNK_OVERLAP = int(os.getenv('RAG_LATEX_CHUNK_OVERLAP', '300'))
MAX_FILE_SIZE = int(os.getenv('RAG_MAX_FILE_SIZE', '10485760')) # 10MB
# Git processing
MAX_COMMITS = int(os.getenv('RAG_MAX_COMMITS', '1000'))
GIT_LOG_TIMEOUT = int(os.getenv('RAG_GIT_LOG_TIMEOUT', '60'))
GIT_DIFF_TIMEOUT = int(os.getenv('RAG_GIT_DIFF_TIMEOUT', '30'))
GIT_CLONE_TIMEOUT = int(os.getenv('RAG_GIT_CLONE_TIMEOUT', '300'))
GIT_VERIFY_TIMEOUT = int(os.getenv('RAG_GIT_VERIFY_TIMEOUT', '10'))
# Search configuration
DEFAULT_SEARCH_LIMIT = int(os.getenv('RAG_DEFAULT_SEARCH_LIMIT', '5'))
DEFAULT_TICKET_SEARCH_LIMIT = int(os.getenv('RAG_DEFAULT_TICKET_SEARCH_LIMIT', '10'))
MAX_SEARCH_LIMIT = int(os.getenv('RAG_MAX_SEARCH_LIMIT', '20'))
# File processing
@staticmethod
def get_supported_extensions():
extensions_str = os.getenv('RAG_SUPPORTED_EXTENSIONS',
'py,js,ts,jsx,tsx,java,cpp,c,h,cs,php,rb,go,rs,swift,kt,scala,md,txt,rst,org,tex,json,yaml,yml,xml,html,css,sql,sh,bash,zsh,dockerfile,gitignore,env,toml,ini,cfg')
return {f'.{ext.strip()}' for ext in extensions_str.split(',')}
@staticmethod
def get_ignored_directories():
dirs_str = os.getenv('RAG_IGNORE_DIRECTORIES',
'node_modules,__pycache__,venv,.venv,env,.env,target,build,.gradle,.m2,bin,obj,vendor,.idea,.vscode,.vs,.DS_Store,logs,tmp,temp,dist,out,.pytest_cache,.git,.svn')
return {dir.strip() for dir in dirs_str.split(',')}
# Database
SCHEMA_VERSION = int(os.getenv('RAG_SCHEMA_VERSION', '2'))
# Performance
PROCESSING_THREADS = int(os.getenv('RAG_PROCESSING_THREADS', '4'))
VECTOR_BATCH_SIZE = int(os.getenv('RAG_VECTOR_BATCH_SIZE', '100'))
# Security
ALLOW_EXECUTABLE_FILES = os.getenv('RAG_ALLOW_EXECUTABLE_FILES', 'false').lower() == 'true'
MAX_PATH_DEPTH = int(os.getenv('RAG_MAX_PATH_DEPTH', '10'))
# Development
DEV_MODE = os.getenv('RAG_DEV_MODE', 'false').lower() == 'true'
SKIP_FILE_VALIDATION = os.getenv('RAG_SKIP_FILE_VALIDATION', 'false').lower() == 'true'
def timestamp() -> str:
"""Return current timestamp"""
return datetime.now().isoformat()
class DatabaseManager:
"""Manages database schema and migrations"""
CURRENT_SCHEMA_VERSION = Config.SCHEMA_VERSION
def __init__(self, db_path: str):
self.db_path = Path(db_path)
self.db_path.parent.mkdir(parents=True, exist_ok=True)
def get_current_version(self) -> int:
"""Get the current schema version from the database"""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Check if schema_version table exists
cursor.execute("""
SELECT name FROM sqlite_master
WHERE type='table' AND name='schema_version'
""")
if not cursor.fetchone():
conn.close()
return 0 # No schema version table means version 0
# Get the latest version
cursor.execute("SELECT MAX(version) FROM schema_version")
result = cursor.fetchone()
conn.close()
return result[0] if result[0] is not None else 0
except Exception as e:
print(f"Error getting schema version: {e}")
return 0
def migrate_to_current(self) -> bool:
"""Migrate database to current schema version"""
current_version = self.get_current_version()
if current_version >= self.CURRENT_SCHEMA_VERSION:
return True
print(f"Migrating database from version {current_version} to {self.CURRENT_SCHEMA_VERSION}")
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Create schema version table if it doesn't exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS schema_version (
version INTEGER PRIMARY KEY,
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
description TEXT
)
''')
# Create/update tables with all necessary columns
cursor.execute('''
CREATE TABLE IF NOT EXISTS sources (
id TEXT PRIMARY KEY,
source_type TEXT NOT NULL,
source_path TEXT NOT NULL,
source_url TEXT,
commit_hash TEXT,
last_indexed TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
file_count INTEGER DEFAULT 0,
chunk_count INTEGER DEFAULT 0,
commit_count INTEGER DEFAULT 0,
last_commit_processed TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS files (
id TEXT PRIMARY KEY,
source_id TEXT NOT NULL,
file_path TEXT NOT NULL,
file_hash TEXT NOT NULL,
last_modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
chunk_count INTEGER DEFAULT 0,
file_size INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (source_id) REFERENCES sources (id) ON DELETE CASCADE
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS git_commits (
id TEXT PRIMARY KEY,
source_id TEXT NOT NULL,
repository_path TEXT NOT NULL,
commit_hash TEXT NOT NULL,
author_name TEXT NOT NULL,
author_email TEXT NOT NULL,
commit_date TEXT NOT NULL,
subject TEXT NOT NULL,
body TEXT,
ticket_ids TEXT,
files_changed TEXT,
chunk_count INTEGER DEFAULT 0,
processed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (source_id) REFERENCES sources (id) ON DELETE CASCADE
)
''')
# Add missing columns to existing tables (gracefully handle existing columns)
columns_to_add = [
('sources', 'commit_count', 'INTEGER DEFAULT 0'),
('sources', 'last_commit_processed', 'TEXT'),
('sources', 'created_at', 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP'),
('sources', 'updated_at', 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP'),
('files', 'file_size', 'INTEGER'),
('files', 'created_at', 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP'),
('files', 'updated_at', 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP'),
('git_commits', 'repository_path', 'TEXT NOT NULL DEFAULT ""'),
('git_commits', 'processed_at', 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP'),
('git_commits', 'created_at', 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP'),
]
for table, column, definition in columns_to_add:
try:
cursor.execute(f'ALTER TABLE {table} ADD COLUMN {column} {definition}')
except sqlite3.OperationalError as e:
if "duplicate column name" not in str(e).lower():
print(f"Warning: Could not add {column} to {table}: {e}")
# Create indexes
indexes = [
'CREATE INDEX IF NOT EXISTS idx_sources_type ON sources(source_type)',
'CREATE INDEX IF NOT EXISTS idx_sources_last_indexed ON sources(last_indexed)',
'CREATE INDEX IF NOT EXISTS idx_files_source_id ON files(source_id)',
'CREATE INDEX IF NOT EXISTS idx_files_hash ON files(file_hash)',
'CREATE INDEX IF NOT EXISTS idx_files_modified ON files(last_modified)',
'CREATE INDEX IF NOT EXISTS idx_git_commits_source_id ON git_commits(source_id)',
'CREATE INDEX IF NOT EXISTS idx_git_commits_hash ON git_commits(commit_hash)',
'CREATE INDEX IF NOT EXISTS idx_git_commits_repo_path ON git_commits(repository_path)',
'CREATE INDEX IF NOT EXISTS idx_git_commits_source_repo_date ON git_commits(source_id, repository_path, commit_date)',
'CREATE INDEX IF NOT EXISTS idx_git_commits_ticket_ids ON git_commits(ticket_ids)',
'CREATE INDEX IF NOT EXISTS idx_git_commits_processed_at ON git_commits(processed_at)',
'CREATE UNIQUE INDEX IF NOT EXISTS idx_files_unique ON files(source_id, file_path)',
'CREATE UNIQUE INDEX IF NOT EXISTS idx_commits_unique ON git_commits(source_id, repository_path, commit_hash)',
]
for index_sql in indexes:
try:
cursor.execute(index_sql)
except sqlite3.OperationalError as e:
print(f"Warning: Could not create index: {e}")
# Update schema version
cursor.execute(
'INSERT OR REPLACE INTO schema_version (version, description) VALUES (?, ?)',
(self.CURRENT_SCHEMA_VERSION, 'Complete schema with git commits and repository tracking')
)
conn.commit()
conn.close()
print(f"✓ Database migrated to version {self.CURRENT_SCHEMA_VERSION}")
return True
except Exception as e:
print(f"Error migrating database: {e}")
return False
class GitCommitProcessor:
"""Handles Git commit parsing and processing"""
def __init__(self):
self.ticket_pattern = re.compile(r'\b([A-Z]+-\d+)\b', re.IGNORECASE)
def extract_ticket_ids(self, message: str) -> List[str]:
"""Extract ticket IDs from commit messages (e.g., GET-1903, JIRA-123)"""
matches = self.ticket_pattern.findall(message.upper())
return list(set(matches)) # Remove duplicates
def get_git_commits(self, repo_path: Path, max_commits: int = None, since_commit: Optional[str] = None) -> List[Dict]:
"""Extract commit information from a Git repository"""
commits = []
max_commits = max_commits or Config.MAX_COMMITS
try:
# Build git log command
cmd = [
"git", "log",
f"--max-count={max_commits}",
"--pretty=format:%H|%an|%ae|%ad|%s|%b",
"--date=iso",
"--name-status"
]
# If we have a since_commit, only get commits after it
if since_commit:
cmd.append(f"{since_commit}..HEAD")
result = subprocess.run(
cmd,
cwd=repo_path,
capture_output=True,
text=True,
timeout=Config.GIT_LOG_TIMEOUT
)
if result.returncode != 0:
print(f"Error getting git log: {result.stderr}")
return commits
# Parse the output
current_commit = None
files_section = False
for line in result.stdout.split('\n'):
line = line.strip()
if not line:
if current_commit and files_section:
# End of current commit
commits.append(current_commit)
current_commit = None
files_section = False
continue
if '|' in line and not files_section:
# This is a commit header line
if current_commit:
commits.append(current_commit)
parts = line.split('|', 5)
if len(parts) >= 5:
hash_val, author_name, author_email, date_str, subject = parts[:5]
body = parts[5] if len(parts) > 5 else ""
full_message = f"{subject}\n{body}".strip()
ticket_ids = self.extract_ticket_ids(full_message)
current_commit = {
'hash': hash_val,
'author_name': author_name,
'author_email': author_email,
'date': date_str,
'subject': subject,
'body': body,
'full_message': full_message,
'ticket_ids': ticket_ids,
'files_changed': []
}
files_section = True
elif files_section and current_commit:
# This is a file change line (M, A, D, etc.)
if line and not line.startswith('commit'):
parts = line.split('\t', 1)
if len(parts) == 2:
change_type, file_path = parts
current_commit['files_changed'].append({
'type': change_type,
'path': file_path
})
# Don't forget the last commit
if current_commit:
commits.append(current_commit)
except subprocess.TimeoutExpired:
print("Timeout getting git commits")
except Exception as e:
print(f"Error processing git commits: {e}")
return commits
def get_commit_diff(self, repo_path: Path, commit_hash: str) -> str:
"""Get the diff for a specific commit"""
try:
result = subprocess.run(
["git", "show", "--pretty=format:", "--name-status", commit_hash],
cwd=repo_path,
capture_output=True,
text=True,
timeout=Config.GIT_DIFF_TIMEOUT
)
if result.returncode == 0:
return result.stdout
else:
return ""
except Exception as e:
print(f"Error getting commit diff for {commit_hash}: {e}")
return ""
class LatexAwareDocumentProcessor:
"""Enhanced document processor with LaTeX-specific chunking strategies"""
def __init__(self, chunk_size: int = None, chunk_overlap: int = None):
self.chunk_size = chunk_size or Config.LATEX_CHUNK_SIZE
self.chunk_overlap = chunk_overlap or Config.LATEX_CHUNK_OVERLAP
self.tokenizer = tiktoken.get_encoding("cl100k_base")
# LaTeX structure patterns
self.section_patterns = [
r'\\section\*?\{([^}]+)\}',
r'\\subsection\*?\{([^}]+)\}',
r'\\subsubsection\*?\{([^}]+)\}',
r'\\chapter\*?\{([^}]+)\}',
r'\\part\*?\{([^}]+)\}'
]
# Math environment patterns
self.math_env_patterns = [
r'\\begin\{equation\*?\}.*?\\end\{equation\*?\}',
r'\\begin\{align\*?\}.*?\\end\{align\*?\}',
r'\\begin\{gather\*?\}.*?\\end\{gather\*?\}',
r'\\begin\{multline\*?\}.*?\\end\{multline\*?\}',
r'\\\[.*?\\\]',
r'\$\$.*?\$\$'
]
# Theorem-like environments
self.theorem_patterns = [
r'\\begin\{theorem\}.*?\\end\{theorem\}',
r'\\begin\{lemma\}.*?\\end\{lemma\}',
r'\\begin\{proposition\}.*?\\end\{proposition\}',
r'\\begin\{corollary\}.*?\\end\{corollary\}',
r'\\begin\{definition\}.*?\\end\{definition\}',
r'\\begin\{proof\}.*?\\end\{proof\}',
r'\\begin\{example\}.*?\\end\{example\}',
r'\\begin\{remark\}.*?\\end\{remark\}'
]
def chunk_text(self, text: str, metadata: Dict) -> List[Dict]:
"""Enhanced chunking with LaTeX awareness"""
if not text.strip():
return []
file_extension = metadata.get('file_type', '').lower()
if file_extension == '.tex':
return self._chunk_latex(text, metadata)
else:
return self._chunk_generic(text, metadata)
def _chunk_latex(self, text: str, metadata: Dict) -> List[Dict]:
"""LaTeX-specific chunking strategy"""
chunks = []
# First, identify major structural elements
structural_elements = self._identify_latex_structure(text)
# Process each structural element
for element in structural_elements:
element_chunks = self._process_latex_element(element, metadata)
chunks.extend(element_chunks)
return chunks
def _identify_latex_structure(self, text: str) -> List[Dict]:
"""Identify major structural components in LaTeX document"""
elements = []
lines = text.split('\n')
current_element = {'type': 'preamble', 'content': [], 'metadata': {}}
in_document = False
i = 0
while i < len(lines):
line = lines[i].strip()
# Document boundaries
if '\\begin{document}' in line:
if current_element['content']:
elements.append(current_element)
current_element = {'type': 'document_start', 'content': [line], 'metadata': {}}
in_document = True
i += 1
continue
elif '\\end{document}' in line:
if current_element['content']:
elements.append(current_element)
elements.append({'type': 'document_end', 'content': [line], 'metadata': {}})
break
if not in_document:
current_element['content'].append(line)
i += 1
continue
# Check for section headers
section_match = self._match_section(line)
if section_match:
if current_element['content']:
elements.append(current_element)
current_element = {
'type': 'section',
'content': [line],
'metadata': {
'section_type': section_match['type'],
'section_title': section_match['title'],
'level': section_match['level']
}
}
i += 1
continue
# Check for theorem-like environments
theorem_block = self._extract_environment_block(lines, i, self.theorem_patterns)
if theorem_block:
if current_element['content']:
elements.append(current_element)
elements.append({
'type': 'theorem',
'content': theorem_block['content'],
'metadata': {'env_type': theorem_block['env_type']}
})
current_element = {'type': 'content', 'content': [], 'metadata': {}}
i = theorem_block['end_index']
continue
# Check for math environments
math_block = self._extract_environment_block(lines, i, self.math_env_patterns)
if math_block:
if current_element['content']:
elements.append(current_element)
elements.append({
'type': 'math',
'content': math_block['content'],
'metadata': {'env_type': math_block['env_type']}
})
current_element = {'type': 'content', 'content': [], 'metadata': {}}
i = math_block['end_index']
continue
# Regular content
current_element['content'].append(line)
i += 1
if current_element['content']:
elements.append(current_element)
return elements
def _match_section(self, line: str) -> Optional[Dict]:
"""Match section headers and extract metadata"""
section_levels = {
'part': 0,
'chapter': 1,
'section': 2,
'subsection': 3,
'subsubsection': 4
}
for pattern in self.section_patterns:
match = re.search(pattern, line)
if match:
section_type = re.search(r'\\(\w+)', line).group(1)
return {
'type': section_type,
'title': match.group(1),
'level': section_levels.get(section_type, 5)
}
return None
def _extract_environment_block(self, lines: List[str], start_idx: int, patterns: List[str]) -> Optional[Dict]:
"""Extract complete environment blocks (theorem, equation, etc.)"""
# Check if current line starts an environment
current_line = lines[start_idx]
for pattern in patterns:
# Handle single-line patterns (like \[...\] or $$...$$)
single_line_match = re.search(pattern, current_line, re.DOTALL)
if single_line_match and not ('\\begin{' in pattern):
return {
'content': [current_line],
'end_index': start_idx + 1,
'env_type': 'inline_math'
}
# Handle multi-line environments
begin_match = re.search(r'\\begin\{(\w+\*?)\}', current_line)
if begin_match:
env_name = begin_match.group(1)
end_pattern = f'\\\\end{{{env_name}}}'
# Find the end of this environment
content = [current_line]
for i in range(start_idx + 1, len(lines)):
content.append(lines[i])
if re.search(end_pattern, lines[i]):
return {
'content': content,
'end_index': i + 1,
'env_type': env_name
}
return None
def _process_latex_element(self, element: Dict, base_metadata: Dict) -> List[Dict]:
"""Process individual LaTeX elements into chunks"""
content = '\n'.join(element['content'])
# Combine base metadata with element-specific metadata
chunk_metadata = {**base_metadata, **element.get('metadata', {})}
chunk_metadata['element_type'] = element['type']
# For small elements, keep them whole
if len(content) <= self.chunk_size:
return [{
'content': content,
'metadata': chunk_metadata
}]
# For large elements, split more carefully
if element['type'] in ['theorem', 'math']:
# Keep mathematical content together as much as possible
return self._split_mathematical_content(content, chunk_metadata)
elif element['type'] == 'section':
# Split section content at paragraph boundaries
return self._split_section_content(content, chunk_metadata)
else:
# Default splitting for other content
return self._split_generic_content(content, chunk_metadata)
def _split_mathematical_content(self, content: str, metadata: Dict) -> List[Dict]:
"""Split mathematical content while preserving coherence"""
chunks = []
# Try to split at logical boundaries within math content
# Look for \\ (line breaks in math), blank lines, or comment lines
split_points = []
lines = content.split('\n')
for i, line in enumerate(lines):
if (line.strip() == '' or
line.strip().startswith('%') or
'\\\\' in line):
split_points.append(i)
if not split_points:
# If no good split points, just return as single chunk
return [{'content': content, 'metadata': metadata}]
# Create chunks at split points
current_chunk = []
for i, line in enumerate(lines):
current_chunk.append(line)
if i in split_points and len('\n'.join(current_chunk)) >= self.chunk_size // 2:
chunks.append({
'content': '\n'.join(current_chunk),
'metadata': metadata
})
current_chunk = []
if current_chunk:
chunks.append({
'content': '\n'.join(current_chunk),
'metadata': metadata
})
return chunks
def _split_section_content(self, content: str, metadata: Dict) -> List[Dict]:
"""Split section content at natural boundaries"""
# Split at paragraph boundaries (double newlines)
paragraphs = re.split(r'\n\s*\n', content)
chunks = []
current_chunk = []
current_size = 0
for paragraph in paragraphs:
para_size = len(paragraph)
if current_size + para_size > self.chunk_size and current_chunk:
# Save current chunk
chunks.append({
'content': '\n\n'.join(current_chunk),
'metadata': metadata
})
current_chunk = [paragraph]
current_size = para_size
else:
current_chunk.append(paragraph)
current_size += para_size
if current_chunk:
chunks.append({
'content': '\n\n'.join(current_chunk),
'metadata': metadata
})
return chunks
def _split_generic_content(self, content: str, metadata: Dict) -> List[Dict]:
"""Generic content splitting with overlap"""
chunks = []
words = content.split()
current_chunk = []
current_size = 0
for word in words:
word_size = len(word) + 1 # +1 for space
if current_size + word_size > self.chunk_size and current_chunk:
chunk_text = ' '.join(current_chunk)
chunks.append({
'content': chunk_text,
'metadata': metadata
})
# Create overlap
overlap_words = []
overlap_size = 0
for w in reversed(current_chunk):
if overlap_size + len(w) <= self.chunk_overlap:
overlap_words.insert(0, w)
overlap_size += len(w) + 1
else:
break
current_chunk = overlap_words + [word]
current_size = sum(len(w) + 1 for w in current_chunk)
else:
current_chunk.append(word)
current_size += word_size
if current_chunk:
chunks.append({
'content': ' '.join(current_chunk),
'metadata': metadata
})
return chunks
def _chunk_generic(self, text: str, metadata: Dict) -> List[Dict]:
"""Generic chunking for non-LaTeX files"""
sentences = text.replace('\n', ' ').split('. ')
chunks = []
current_chunk = ""
for sentence in sentences:
sentence = sentence.strip()
if not sentence:
continue
test_chunk = current_chunk + ". " + sentence if current_chunk else sentence
if len(self.tokenizer.encode(test_chunk)) > self.chunk_size and current_chunk:
chunks.append({
'content': current_chunk.strip(),
'metadata': metadata
})
current_chunk = sentence
else:
current_chunk = test_chunk
if current_chunk:
chunks.append({
'content': current_chunk.strip(),
'metadata': metadata
})
return chunks
class DocumentProcessor:
"""Handles document parsing and chunking with LaTeX support"""
@property
def SUPPORTED_EXTENSIONS(self):
return Config.get_supported_extensions()
@property
def IGNORE_DIRECTORIES(self):
return Config.get_ignored_directories()
# File patterns to ignore
IGNORE_FILE_PATTERNS = {
# Compiled files
'*.pyc', '*.pyo', '*.pyd', '*.so', '*.dll', '*.dylib', '*.exe',
'*.class', '*.jar', '*.war', '*.ear',
'*.o', '*.obj', '*.lib', '*.a',
# Package files
'*.zip', '*.tar', '*.tar.gz', '*.tgz', '*.rar', '*.7z',
'*.deb', '*.rpm', '*.msi',
# Lock files
'package-lock.json', 'yarn.lock', 'Pipfile.lock', 'poetry.lock',
'Gemfile.lock', 'composer.lock', 'Cargo.lock',
# Log files
'*.log', '*.out', '*.err',
# Database files
'*.db', '*.sqlite', '*.sqlite3',
# Media files (usually too large and not useful for code analysis)
'*.jpg', '*.jpeg', '*.png', '*.gif', '*.bmp', '*.svg', '*.ico',
'*.mp3', '*.mp4', '*.avi', '*.mov', '*.wmv', '*.pdf',
# IDE files
'*.swp', '*.swo', '*~', '.DS_Store', 'Thumbs.db',
# Environment files (may contain secrets)
'.env', '.env.local', '.env.production', '.env.development'
}
def __init__(self, chunk_size: int = None, chunk_overlap: int = None):
self.chunk_size = chunk_size or Config.CHUNK_SIZE
self.chunk_overlap = chunk_overlap or Config.CHUNK_OVERLAP
self.tokenizer = tiktoken.get_encoding("cl100k_base")
# Initialize the LaTeX-aware processor
self.latex_processor = LatexAwareDocumentProcessor(self.chunk_size, self.chunk_overlap)
def should_process_file(self, file_path: Path) -> bool:
"""Check if file should be processed"""
# Check file extension
if file_path.suffix.lower() not in self.SUPPORTED_EXTENSIONS:
return False
# Check if file is in an ignored directory
path_parts = file_path.parts
for part in path_parts:
if part.lower() in self.IGNORE_DIRECTORIES:
return False
# Check file name patterns
import fnmatch
file_name = file_path.name.lower()
for pattern in self.IGNORE_FILE_PATTERNS:
if fnmatch.fnmatch(file_name, pattern.lower()):
return False
# Check file size (skip very large files)
try:
file_size = file_path.stat().st_size
# Skip files larger than configured max size
if file_size > Config.MAX_FILE_SIZE:
return False
# Skip empty files
if file_size == 0:
return False
except OSError:
return False
return True
def extract_text(self, file_path: Path) -> str:
"""Extract text content from file with robust error handling"""
try:
# First, check if file exists and is readable
if not file_path.exists():
print(f"File not found: {file_path}")
return ""
# Check file size
file_size = file_path.stat().st_size
print(f"Processing {file_path} (size: {file_size} bytes)")
# Try multiple encoding strategies
encodings = ['utf-8', 'utf-8-sig', 'latin-1', 'cp1252', 'iso-8859-1']
for encoding in encodings:
try:
with open(file_path, 'r', encoding=encoding, errors='replace') as f:
content = f.read()
# Verify we got reasonable content
if content and len(content.strip()) > 0:
print(f"Successfully read {file_path} with encoding {encoding}")
return content
except UnicodeDecodeError:
continue
except Exception as e:
print(f"Error with encoding {encoding} for {file_path}: {e}")
continue
# If all encodings fail, try binary mode and convert
try:
with open(file_path, 'rb') as f:
raw_data = f.read()
# Try to decode as utf-8 with error handling
content = raw_data.decode('utf-8', errors='replace')
print(f"Read {file_path} in binary mode with error replacement")
return content
except Exception as e:
print(f"Failed to read {file_path} in binary mode: {e}")
return ""
except PermissionError:
print(f"Permission denied: {file_path}")
return ""
except FileNotFoundError:
print(f"File not found: {file_path}")
return ""
except OSError as e:
print(f"OS error reading {file_path}: {e}")
return ""
except Exception as e:
print(f"Unexpected error reading {file_path}: {type(e).__name__}: {e}")
traceback.print_exc()
return ""
def chunk_text(self, text: str, metadata: Dict) -> List[Dict]:
"""Split text into chunks with metadata using LaTeX-aware processing"""
if not text.strip():
return []
# Use the LaTeX-aware processor which handles both LaTeX and generic files
return self.latex_processor.chunk_text(text, metadata)
class GitManager:
"""Handles Git operations"""
@staticmethod
def clone_repo(repo_url: str, target_dir: Path) -> bool:
"""Clone a git repository"""
try:
result = subprocess.run(
["git", "clone", repo_url, str(target_dir)],
capture_output=True,
text=True,
timeout=Config.GIT_CLONE_TIMEOUT
)
return result.returncode == 0
except subprocess.TimeoutExpired:
print(f"Timeout cloning repository: {repo_url}")
return False
except Exception as e:
print(f"Error cloning repository: {e}")
return False
@staticmethod
def get_repo_info(repo_dir: Path) -> Dict[str, str]:
"""Get repository information"""
try:
# Get current commit hash
result = subprocess.run(
["git", "rev-parse", "HEAD"],
cwd=repo_dir,
capture_output=True,
text=True
)
commit_hash = result.stdout.strip() if result.returncode == 0 else "unknown"
return {
'commit_hash': commit_hash,
'last_updated': timestamp()
}
except Exception:
return {
'commit_hash': 'unknown',
'last_updated': timestamp()
}
@staticmethod
def is_git_repo(path: Path) -> bool:
"""Check if path is a git repository"""
# If the path itself is a .git directory
if path.name == '.git':
return True
# Check if path contains a .git directory
git_dir = path / '.git'
return git_dir.exists() and (git_dir.is_dir() or git_dir.is_file())
class RAGPipeline:
"""Main RAG pipeline class with LaTeX support"""
def __init__(self, data_dir: str = None):
self.data_dir = Path(data_dir or Config.DATA_DIR)
self.data_dir.mkdir(exist_ok=True)
# Initialize components with LaTeX support
self.processor = DocumentProcessor()
self.git_processor = GitCommitProcessor()