-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcodebase_expert_fixed.py
More file actions
1745 lines (1453 loc) Β· 73.4 KB
/
codebase_expert_fixed.py
File metadata and controls
1745 lines (1453 loc) Β· 73.4 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
"""
Enhanced Codebase Expert - Universal tool for codebase knowledge
Works with any project to create searchable video memory with better organization
MCP Installation (for Claude Desktop):
The MCP server automatically works with the current directory (cwd) you specify:
{
"mcpServers": {
"codebase-expert": {
"command": "python",
"args": ["/path/to/codebase_expert.py", "serve"],
"cwd": "/path/to/any/project" # MCP will analyze this directory
}
}
}
The MCP server will automatically generate video memory if it doesn't exist.
Standalone Usage:
# Generate video memory with organized output
python codebase_expert.py generate --output-dir ./codebase-memory
# Interactive chat
python codebase_expert.py chat
# Quick question
python codebase_expert.py ask "How does authentication work?"
# Search codebase
python codebase_expert.py search "database implementation"
"""
import os
import sys
import json
import subprocess
import threading
import time
import argparse
import asyncio
from typing import Dict, Any, List, Optional, Tuple
from datetime import datetime
import logging
from pathlib import Path
import fnmatch
import shutil
import zipfile
import io
from contextlib import redirect_stdout, redirect_stderr
# Conditional imports
try:
import mcp.server.stdio
import mcp.types as types
from mcp.server import NotificationOptions, Server
from mcp.server.models import InitializationOptions
MCP_AVAILABLE = True
except ImportError:
MCP_AVAILABLE = False
try:
from memvid import MemvidEncoder, MemvidRetriever, MemvidChat
MEMVID_AVAILABLE = True
except ImportError:
MEMVID_AVAILABLE = False
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Code generation constants
DEFAULT_IGNORE_PATTERNS = [
'.git', '.gitignore', 'node_modules', 'vendor', '__pycache__', '*.pyc', '*.pyo', '*.pyd',
'.DS_Store', '*.log', '*.out', 'coverage', 'dist', 'build', '.env', '.env.*',
'*.swp', '*.swo', '*~', 'venv', 'myenv', '.vscode', '.idea', '*.mp4', '*.json',
'codebase_memory.mp4', 'codebase_index.json', '__pycache__', '.pytest_cache',
'.mypy_cache', '.ruff_cache', 'target', 'Cargo.lock', 'package-lock.json',
'yarn.lock', 'pnpm-lock.yaml', '.next', '.nuxt', '.svelte-kit'
]
CODE_EXTENSIONS = [
# Web
'.ts', '.tsx', '.js', '.jsx', '.vue', '.svelte',
# Backend
'.py', '.java', '.go', '.rs', '.rb', '.php', '.cs', '.cpp', '.c', '.h',
# Config
'.yml', '.yaml', '.json', '.toml', '.ini', '.conf',
# Web assets
'.html', '.css', '.scss', '.sass', '.less',
# Scripts
'.sh', '.bash', '.zsh', '.ps1', '.bat',
# Documentation
'.md', '.rst', '.txt',
# Database
'.sql', '.prisma',
# Docker
'.dockerfile', 'Dockerfile', 'docker-compose.yml',
# Other
'.xml', '.gradle', '.cmake', 'Makefile', '.env.example'
]
class CodebaseExpert:
"""Enhanced expert class with better organization and features."""
def __init__(self, base_path: Optional[str] = None, output_dir: Optional[str] = None):
self.base_path = base_path or os.getcwd()
self.project_name = self.detect_project_name()
# Output directory management
if output_dir:
# Use provided output directory
self.output_dir = output_dir
else:
# Default to organized folder name
self.output_dir = os.path.join(self.base_path, f"codebase-memory-{self.project_name}")
self.video_path = os.path.join(self.output_dir, "codebase_memory.mp4")
self.index_path = os.path.join(self.output_dir, "codebase_index.json")
self.faiss_path = os.path.join(self.output_dir, "codebase_index.faiss")
self.metadata_path = os.path.join(self.output_dir, "metadata.json")
# Keep track of whether we're using the old location
self._using_old_location = False
# Fallback to old location if it exists (only when not explicitly setting output_dir)
# and only for reading existing files, not for generation
if not output_dir:
old_video = os.path.join(self.base_path, "codebase_memory.mp4")
old_index = os.path.join(self.base_path, "codebase_index.json")
if os.path.exists(old_video) and os.path.exists(old_index):
# Use old location for reading if new location doesn't have files
if not os.path.exists(self.video_path):
self.video_path = old_video
self.index_path = old_index
self.output_dir = self.base_path
self._using_old_location = True
self.retriever = None
self.video_generation_in_progress = False
self.video_generation_start_time = None
# File watching for real-time updates
self.file_watcher = None
self.watch_enabled = False
self.change_queue = []
self.last_update_time = None
# MCP server if available
self.server = Server("Codebase Expert") if MCP_AVAILABLE else None
def detect_project_name(self) -> str:
"""Detect project name from various sources."""
# Try package.json
package_json = os.path.join(self.base_path, "package.json")
if os.path.exists(package_json):
try:
with open(package_json, 'r') as f:
data = json.load(f)
return data.get('name', 'project')
except:
pass
# Try setup.py or pyproject.toml
for file in ['setup.py', 'pyproject.toml']:
path = os.path.join(self.base_path, file)
if os.path.exists(path):
try:
with open(path, 'r') as f:
content = f.read()
if 'name' in content:
# Simple extraction
import re
match = re.search(r'name\s*=\s*["\']([^"\']+)["\']', content)
if match:
return match.group(1)
except:
pass
# Try Cargo.toml
cargo_toml = os.path.join(self.base_path, "Cargo.toml")
if os.path.exists(cargo_toml):
try:
with open(cargo_toml, 'r') as f:
content = f.read()
import re
match = re.search(r'name\s*=\s*"([^"]+)"', content)
if match:
return match.group(1)
except:
pass
# Use directory name
return os.path.basename(self.base_path)
def ensure_dependencies(self):
"""Ensure required dependencies are installed."""
if not MEMVID_AVAILABLE:
print("Installing required dependencies...")
subprocess.run([sys.executable, "-m", "pip", "install", "memvid"], check=True)
if MCP_AVAILABLE is False:
subprocess.run([sys.executable, "-m", "pip", "install", "mcp"], check=True)
print("Dependencies installed. Please restart the script.")
sys.exit(0)
def video_exists(self) -> bool:
"""Check if video and index exist."""
return os.path.exists(self.video_path) and os.path.exists(self.index_path)
def initialize_memvid(self):
"""Initialize memvid components."""
if not MEMVID_AVAILABLE:
raise ImportError("Memvid not available")
# Suppress initialization messages
import logging
old_level = logging.root.level
logging.root.setLevel(logging.CRITICAL)
try:
with io.StringIO() as buf, redirect_stdout(buf), redirect_stderr(buf):
self.retriever = MemvidRetriever(self.video_path, self.index_path)
except Exception as e:
raise
finally:
logging.root.setLevel(old_level)
def detect_project_type(self) -> str:
"""Detect the type of project."""
types = []
# Check for various project files
if os.path.exists(os.path.join(self.base_path, "package.json")):
types.append("Node.js/JavaScript")
if os.path.exists(os.path.join(self.base_path, "requirements.txt")) or \
os.path.exists(os.path.join(self.base_path, "setup.py")) or \
os.path.exists(os.path.join(self.base_path, "pyproject.toml")):
types.append("Python")
if os.path.exists(os.path.join(self.base_path, "Cargo.toml")):
types.append("Rust")
if os.path.exists(os.path.join(self.base_path, "go.mod")):
types.append("Go")
if os.path.exists(os.path.join(self.base_path, "pom.xml")) or \
os.path.exists(os.path.join(self.base_path, "build.gradle")):
types.append("Java")
if os.path.exists(os.path.join(self.base_path, "Gemfile")):
types.append("Ruby")
if os.path.exists(os.path.join(self.base_path, ".csproj")) or \
any(f.endswith('.sln') for f in os.listdir(self.base_path) if os.path.isfile(os.path.join(self.base_path, f))):
types.append("C#/.NET")
return " + ".join(types) if types else "general"
# Video generation methods
def read_gitignore(self, path: str) -> List[str]:
"""Read gitignore patterns."""
gitignore_path = os.path.join(path, '.gitignore')
patterns = []
if os.path.exists(gitignore_path):
with open(gitignore_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
patterns.append(line)
return patterns
def should_ignore(self, file_path: str, ignore_patterns: List[str]) -> bool:
"""Check if file should be ignored."""
file_name = os.path.basename(file_path)
for pattern in ignore_patterns:
if fnmatch.fnmatch(file_name, pattern):
return True
if pattern.endswith('/'):
if any(part == pattern[:-1] for part in file_path.split(os.sep)):
return True
if fnmatch.fnmatch(file_path, pattern):
return True
parts = file_path.split(os.sep)
for i in range(len(parts)):
if fnmatch.fnmatch(parts[i], pattern):
return True
return False
def has_code_extension(self, file_path: str) -> bool:
"""Check if file has code extension."""
return any(file_path.lower().endswith(ext) for ext in CODE_EXTENSIONS)
def split_large_content(self, content: str, max_size: int = 600) -> List[str]:
"""Split large content into semantic chunks with improved handling."""
if len(content) <= max_size:
return [content]
chunks = []
lines = content.split('\n')
# Detect file type for better chunking
file_ext = self._detect_content_type(lines[:50]) # Check first 50 lines
if file_ext in ['.py', '.java', '.go', '.rs', '.cs', '.cpp']:
# Language-aware chunking for structured languages
chunks = self._split_by_semantic_blocks(lines, max_size)
else:
# Fallback to line-based chunking with overlap
chunks = self._split_with_overlap(lines, max_size)
return chunks
def _detect_content_type(self, lines: List[str]) -> str:
"""Detect content type from first few lines."""
content_sample = '\n'.join(lines[:10])
# Python
if 'import ' in content_sample or 'from ' in content_sample or 'def ' in content_sample:
return '.py'
# JavaScript/TypeScript
elif 'const ' in content_sample or 'function ' in content_sample or 'import {' in content_sample:
return '.js'
# Java
elif 'package ' in content_sample or 'public class' in content_sample:
return '.java'
# Go
elif 'package main' in content_sample or 'func ' in content_sample:
return '.go'
# Rust
elif 'fn ' in content_sample or 'use ' in content_sample:
return '.rs'
return '.txt'
def _split_by_semantic_blocks(self, lines: List[str], max_size: int) -> List[str]:
"""Split code by semantic blocks (functions, classes, etc.)."""
chunks = []
current_block = []
current_size = 0
indent_stack = [0] # Track indentation levels
for i, line in enumerate(lines):
# Detect semantic boundaries
stripped = line.lstrip()
indent = len(line) - len(stripped)
# Check if this is a new top-level block
is_new_block = (
(stripped.startswith(('def ', 'class ', 'function ', 'func ', 'public ', 'private '))
and indent <= indent_stack[0]) or
(i > 0 and not stripped and current_size > max_size * 0.7) # Empty line when chunk is getting large
)
if is_new_block and current_size > max_size * 0.5 and current_block:
# Save current block
chunks.append('\n'.join(current_block))
current_block = []
current_size = 0
indent_stack = [indent]
# Add line to current block
current_block.append(line)
current_size += len(line) + 1
# Update indent tracking
if stripped:
if indent > indent_stack[-1]:
indent_stack.append(indent)
elif indent < indent_stack[-1]:
while indent_stack and indent < indent_stack[-1]:
indent_stack.pop()
# Force split if block is too large
if current_size > max_size:
chunks.append('\n'.join(current_block))
current_block = []
current_size = 0
indent_stack = [0]
if current_block:
chunks.append('\n'.join(current_block))
return chunks
def _split_with_overlap(self, lines: List[str], max_size: int) -> List[str]:
"""Split content with overlap for better context preservation."""
chunks = []
overlap_lines = 5 # Number of lines to overlap
current_chunk = []
current_size = 0
for i, line in enumerate(lines):
line_size = len(line) + 1
if current_size + line_size > max_size and current_chunk:
chunks.append('\n'.join(current_chunk))
# Keep last few lines for context
if len(current_chunk) > overlap_lines:
current_chunk = current_chunk[-overlap_lines:]
current_size = sum(len(l) + 1 for l in current_chunk)
else:
current_chunk = []
current_size = 0
current_chunk.append(line)
current_size += line_size
if current_chunk:
chunks.append('\n'.join(current_chunk))
return chunks
def extract_code_chunks(self, scan_path: str, relative_to: str) -> Tuple[List[str], List[str]]:
"""Extract code chunks from directory."""
chunks = []
ignore_patterns = DEFAULT_IGNORE_PATTERNS + self.read_gitignore(scan_path)
total_files = 0
file_list = []
for root, dirs, files in os.walk(scan_path):
dirs[:] = [d for d in dirs if not self.should_ignore(os.path.join(root, d), ignore_patterns)]
for file in files:
file_path = os.path.join(root, file)
relative_path = os.path.relpath(file_path, relative_to)
if self.should_ignore(relative_path, ignore_patterns):
continue
if not self.has_code_extension(file_path):
continue
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
if not content.strip():
continue
total_files += 1
file_list.append(relative_path)
# Check file size and handle accordingly
file_size = len(content)
if file_size > 50000: # Large file (>50KB)
logger.info(f"Processing large file: {relative_path} ({file_size/1024:.1f}KB)")
content_chunks = self.split_large_content(content)
for i, chunk_content in enumerate(content_chunks):
if len(content_chunks) > 1:
# Add context about chunk position
chunk = f"=== {relative_path} (part {i+1}/{len(content_chunks)}) ===\n\n{chunk_content}\n"
else:
chunk = f"=== {relative_path} ===\n\n{chunk_content}\n"
chunks.append(chunk)
except Exception as e:
logger.error(f"Error reading {file_path}: {e}")
print(f"Processed {total_files} files into {len(chunks)} chunks")
return chunks, file_list
def generate_context_chunks(self, file_list: List[str]) -> List[str]:
"""Generate special context chunks for better RAG quality."""
context_chunks = []
# 1. Project Overview Chunk
overview = f"""=== PROJECT OVERVIEW ===
Project Name: {self.project_name}
Project Type: {self.detect_project_type()}
Base Path: {self.base_path}
Total Files: {len(file_list)}
This is a comprehensive codebase index containing all source code, configuration files, and documentation.
"""
context_chunks.append(overview)
# 2. Folder Structure Chunk
structure = f"""=== FOLDER STRUCTURE ===
{self.get_folder_structure()}
This folder structure represents the organization of the codebase.
"""
context_chunks.append(structure)
# 3. Git History Chunk
git_info = self.get_git_info()
if 'error' not in git_info:
git_chunk = f"""=== GIT HISTORY ===
Current Branch: {git_info.get('current_branch', 'unknown')}
Remote Origin: {git_info.get('remote_origin', 'unknown')}
Recent Commits:
{chr(10).join(git_info.get('recent_commits', [])[:10])}
Top Contributors:
{chr(10).join(git_info.get('top_contributors', [])[:5])}
"""
context_chunks.append(git_chunk)
# 4. File Extensions Summary
extensions = {}
for file in file_list:
ext = os.path.splitext(file)[1]
if ext:
extensions[ext] = extensions.get(ext, 0) + 1
ext_summary = f"""=== FILE TYPES SUMMARY ===
File extensions in this codebase:
"""
for ext, count in sorted(extensions.items(), key=lambda x: x[1], reverse=True):
ext_summary += f"\n{ext}: {count} files"
context_chunks.append(ext_summary)
# 5. README content if exists
for readme_name in ['README.md', 'readme.md', 'README.txt', 'README']:
readme_path = os.path.join(self.base_path, readme_name)
if os.path.exists(readme_path):
try:
with open(readme_path, 'r', encoding='utf-8', errors='ignore') as f:
readme_content = f.read()
if readme_content:
readme_chunk = f"""=== {readme_name} ===
{readme_content}
"""
context_chunks.append(readme_chunk)
break
except:
pass
# 6. Package/Dependency Information
dep_info = self.get_dependency_info()
if dep_info:
dep_chunk = f"""=== DEPENDENCIES ===
{dep_info}
"""
context_chunks.append(dep_chunk)
return context_chunks
def get_dependency_info(self) -> str:
"""Extract dependency information from various package files."""
dep_info = []
# package.json for Node.js
package_json = os.path.join(self.base_path, 'package.json')
if os.path.exists(package_json):
try:
with open(package_json, 'r') as f:
data = json.load(f)
deps = data.get('dependencies', {})
dev_deps = data.get('devDependencies', {})
dep_info.append("Node.js Dependencies:")
for dep, version in list(deps.items())[:20]:
dep_info.append(f" {dep}: {version}")
if len(deps) > 20:
dep_info.append(f" ... and {len(deps) - 20} more")
if dev_deps:
dep_info.append("\nDev Dependencies:")
for dep, version in list(dev_deps.items())[:10]:
dep_info.append(f" {dep}: {version}")
if len(dev_deps) > 10:
dep_info.append(f" ... and {len(dev_deps) - 10} more")
except:
pass
# requirements.txt for Python
requirements = os.path.join(self.base_path, 'requirements.txt')
if os.path.exists(requirements):
try:
with open(requirements, 'r') as f:
lines = f.readlines()
dep_info.append("\nPython Requirements:")
for line in lines[:20]:
line = line.strip()
if line and not line.startswith('#'):
dep_info.append(f" {line}")
if len(lines) > 20:
dep_info.append(f" ... and more")
except:
pass
return "\n".join(dep_info) if dep_info else ""
def get_folder_structure(self, max_depth: int = 3) -> str:
"""Generate a tree-like folder structure."""
structure_lines = []
def add_tree(path: str, prefix: str = "", depth: int = 0):
if depth > max_depth:
return
try:
items = sorted(os.listdir(path))
# Filter out common ignore patterns
items = [item for item in items if not any(
fnmatch.fnmatch(item, pattern) for pattern in ['.git', 'node_modules', '__pycache__', '*.pyc', 'venv', 'myenv']
)]
for i, item in enumerate(items[:20]): # Limit items per folder
item_path = os.path.join(path, item)
is_last = i == len(items) - 1
if os.path.isdir(item_path):
structure_lines.append(f"{prefix}{'βββ ' if is_last else 'βββ '}{item}/")
extension = " " if is_last else "β "
add_tree(item_path, prefix + extension, depth + 1)
else:
structure_lines.append(f"{prefix}{'βββ ' if is_last else 'βββ '}{item}")
if len(items) > 20:
structure_lines.append(f"{prefix}βββ ... ({len(items) - 20} more items)")
except PermissionError:
pass
structure_lines.append(f"{self.project_name}/")
add_tree(self.base_path, "")
return "\n".join(structure_lines)
def _analyze_and_enhance_query(self, question: str) -> List[str]:
"""Analyze query type and generate enhanced search queries."""
queries = [question] # Always include original
# Detect architectural patterns
architectural_keywords = [
'architecture', 'design', 'structure', 'pattern', 'how does',
'how do', 'implementation', 'workflow', 'system', 'component',
'integration', 'relationship', 'interaction'
]
question_lower = question.lower()
is_architectural = any(keyword in question_lower for keyword in architectural_keywords)
if is_architectural:
# Extract key concepts from the question
concepts = self._extract_concepts(question)
# Generate variations
for concept in concepts:
# Add implementation-focused query
queries.append(f"{concept} implementation")
queries.append(f"{concept} class interface")
queries.append(f"{concept} module structure")
# Add overview queries
queries.append("PROJECT OVERVIEW architecture")
queries.append("FOLDER STRUCTURE organization")
# Handle generic searches
if len(question.split()) <= 3: # Short, potentially generic query
# Expand with common patterns
base_terms = question.split()
for term in base_terms:
queries.append(f"class {term}")
queries.append(f"function {term}")
queries.append(f"module {term}")
queries.append(f"{term} configuration")
return queries[:10] # Limit to prevent over-searching
def _extract_concepts(self, text: str) -> List[str]:
"""Extract key concepts from text for query enhancement."""
# Remove common words
stop_words = {
'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for',
'of', 'with', 'by', 'from', 'about', 'into', 'through', 'during',
'how', 'does', 'do', 'what', 'where', 'when', 'why', 'is', 'are',
'was', 'were', 'been', 'being', 'have', 'has', 'had', 'will', 'would',
'could', 'should', 'may', 'might', 'must', 'can', 'this', 'that'
}
words = text.lower().split()
concepts = []
# Extract meaningful words
for word in words:
cleaned = word.strip('.,?!;:\'"')
if cleaned and len(cleaned) > 2 and cleaned not in stop_words:
concepts.append(cleaned)
# Also extract bigrams for compound concepts
for i in range(len(words) - 1):
w1, w2 = words[i].strip('.,?!;:\'"'), words[i+1].strip('.,?!;:\'"')
if w1 not in stop_words and w2 not in stop_words:
concepts.append(f"{w1} {w2}")
return concepts
def _enhance_search_query(self, query: str) -> List[str]:
"""Enhance search query with contextual variations."""
queries = [query] # Original query
# Handle camelCase and snake_case
# Convert camelCase to space-separated
import re
camel_split = re.sub(r'([a-z])([A-Z])', r'\1 \2', query)
if camel_split != query:
queries.append(camel_split.lower())
# Convert snake_case to space-separated
snake_split = query.replace('_', ' ')
if snake_split != query:
queries.append(snake_split)
# Add common programming patterns
if len(query.split()) == 1: # Single word query
word = query.lower()
# Common prefixes/suffixes
queries.extend([
f"get{query}", f"set{query}", f"{query}Handler",
f"{query}Manager", f"{query}Service", f"{query}Controller",
f"handle{query}", f"process{query}", f"create{query}"
])
# File patterns
queries.extend([
f"{word}.py", f"{word}.js", f"{word}.ts",
f"{word}.jsx", f"{word}.tsx", f"{word}.go"
])
# Limit queries to prevent over-searching
return list(dict.fromkeys(queries))[:8]
def _deduplicate_and_rank_results(self, results: List[Dict]) -> List[Dict]:
"""Deduplicate and rank search results by relevance."""
seen_content = {}
ranked_results = []
for result in results:
chunk = result.get('text', '')
# Create content fingerprint
content_key = chunk[:300].strip() # First 300 chars
if content_key in seen_content:
# Update score if this is a better match
existing_idx = seen_content[content_key]
if result.get('score', 0) > ranked_results[existing_idx].get('score', 0):
ranked_results[existing_idx] = result
else:
seen_content[content_key] = len(ranked_results)
ranked_results.append(result)
# Sort by score
return sorted(ranked_results, key=lambda x: x.get('score', 0), reverse=True)
def _get_search_suggestions(self, query: str) -> str:
"""Provide helpful suggestions for failed searches."""
suggestions = ["π‘ Search suggestions:"]
# Check if it's a very generic term
generic_terms = ['config', 'handler', 'manager', 'service', 'util', 'helper', 'controller']
if query.lower() in generic_terms:
suggestions.append(f"- Try being more specific: '{query} authentication' or '{query} database'")
suggestions.append(f"- Search for actual implementations: 'class {query}' or 'function {query}'")
# Suggest file search
suggestions.append(f"- Search for files: '{query}.py' or '{query}.js'")
# Suggest function/class search
suggestions.append(f"- Search for definitions: 'def {query}' or 'class {query}'")
# Suggest exploring project structure
suggestions.append("- Use '/info' to see project structure")
suggestions.append("- Try '/context overview' for project overview")
return "\n".join(suggestions)
def get_git_info(self) -> Dict[str, Any]:
"""Get git repository information."""
git_info = {}
try:
# Check if it's a git repo
subprocess.run(['git', 'rev-parse', '--git-dir'],
cwd=self.base_path, capture_output=True, check=True)
# Get current branch
result = subprocess.run(['git', 'branch', '--show-current'],
cwd=self.base_path, capture_output=True, text=True)
git_info['current_branch'] = result.stdout.strip()
# Get recent commits
result = subprocess.run(['git', 'log', '--oneline', '-10'],
cwd=self.base_path, capture_output=True, text=True)
git_info['recent_commits'] = result.stdout.strip().split('\n')
# Get remote origin
result = subprocess.run(['git', 'remote', 'get-url', 'origin'],
cwd=self.base_path, capture_output=True, text=True)
git_info['remote_origin'] = result.stdout.strip()
# Get contributors
result = subprocess.run(['git', 'shortlog', '-sn', '--all'],
cwd=self.base_path, capture_output=True, text=True)
git_info['top_contributors'] = result.stdout.strip().split('\n')[:5]
except (subprocess.CalledProcessError, FileNotFoundError):
git_info['error'] = 'Not a git repository'
return git_info
def generate_metadata(self, file_list: List[str], chunks: List[str]) -> Dict[str, Any]:
"""Generate enhanced metadata for the codebase."""
total_size = sum(len(chunk) for chunk in chunks)
metadata = {
"project_name": self.project_name,
"project_type": self.detect_project_type(),
"base_path": self.base_path,
"generation_date": datetime.now().isoformat(),
"statistics": {
"total_files": len(file_list),
"total_chunks": len(chunks),
"total_size_mb": total_size / 1024 / 1024,
"unique_extensions": list(set(os.path.splitext(f)[1] for f in file_list if os.path.splitext(f)[1]))
},
"file_list": file_list[:100], # First 100 files
"folder_structure": self.get_folder_structure(),
"git_info": self.get_git_info(),
"memvid_version": "latest",
"expert_version": "1.1.0"
}
return metadata
def create_package(self, include_video_only: bool = False) -> str:
"""Create a zip package with all necessary files."""
package_name = f"{self.project_name}_codebase_memory_{datetime.now().strftime('%Y%m%d_%H%M%S')}.zip"
package_path = os.path.join(self.base_path, package_name)
with zipfile.ZipFile(package_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
# Always include the video
if os.path.exists(self.video_path):
zipf.write(self.video_path, os.path.basename(self.video_path))
if not include_video_only:
# Include index files
if os.path.exists(self.index_path):
zipf.write(self.index_path, os.path.basename(self.index_path))
if os.path.exists(self.faiss_path):
zipf.write(self.faiss_path, os.path.basename(self.faiss_path))
if os.path.exists(self.metadata_path):
zipf.write(self.metadata_path, os.path.basename(self.metadata_path))
# Include a README
readme_content = f"""# {self.project_name} Codebase Memory
Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
Project Type: {self.detect_project_type()}
## Contents
- codebase_memory.mp4: Video containing encoded codebase
- codebase_index.json: Search index for memvid
- codebase_index.faiss: Vector embeddings (if available)
- metadata.json: Project metadata and statistics
## Usage
Place all files in the same directory and use with codebase_expert.py:
```bash
python codebase_expert.py chat --base-path /path/to/extracted/files
```
Or use directly with memvid:
```python
from memvid import MemvidRetriever
retriever = MemvidRetriever("codebase_memory.mp4", "codebase_index.json")
results = retriever.search_with_metadata("your query", top_k=5)
```
"""
zipf.writestr("README.txt", readme_content)
return package_path
def generate_video(self, create_zip: bool = False, video_only_zip: bool = False):
"""Generate the video from codebase with enhanced organization."""
self.ensure_dependencies()
# If we're using old location for reading, reset paths for generation
if self._using_old_location:
self.output_dir = os.path.join(self.base_path, f"codebase-memory-{self.project_name}")
self.video_path = os.path.join(self.output_dir, "codebase_memory.mp4")
self.index_path = os.path.join(self.output_dir, "codebase_index.json")
self.faiss_path = os.path.join(self.output_dir, "codebase_index.faiss")
self.metadata_path = os.path.join(self.output_dir, "metadata.json")
# Create output directory if it doesn't exist
os.makedirs(self.output_dir, exist_ok=True)
print(f"π Scanning {self.project_name} codebase at: {self.base_path}")
print(f"π Output directory: {self.output_dir}")
print("β³ This may take a few minutes for large codebases...")
# Extract all code chunks
all_chunks, file_list = self.extract_code_chunks(self.base_path, self.base_path)
print(f"\nπ Total chunks collected: {len(all_chunks)}")
# Add special context chunks
print("π Adding enhanced context...")
context_chunks = self.generate_context_chunks(file_list)
all_chunks = context_chunks + all_chunks
print(f"π Total chunks with context: {len(all_chunks)}")
if not all_chunks:
print("β No code files found!")
print("Make sure you're in the right directory and have code files.")
return False
# Generate metadata
metadata = self.generate_metadata(file_list, all_chunks)
# Save metadata
with open(self.metadata_path, 'w') as f:
json.dump(metadata, f, indent=2)
print("\n㪠Building video memory...")
encoder = MemvidEncoder()
encoder.add_chunks(all_chunks)
encoder.build_video(
self.video_path,
self.index_path,
show_progress=True
)
# Check if FAISS index was created
if not os.path.exists(self.faiss_path):
# memvid might save it with a different name, try to find it
possible_faiss = os.path.join(self.output_dir, "codebase_index.faiss")
if not os.path.exists(possible_faiss):
possible_faiss = os.path.join(os.path.dirname(self.index_path),
os.path.splitext(os.path.basename(self.index_path))[0] + ".faiss")
if os.path.exists(possible_faiss) and possible_faiss != self.faiss_path:
shutil.copy2(possible_faiss, self.faiss_path)
print(f"\nβ
Video generated successfully!")
print(f"πΉ Video: {self.video_path}")
print(f"π Index: {self.index_path}")
print(f"π Metadata: {self.metadata_path}")
total_size = sum(len(chunk) for chunk in all_chunks)
print(f"\nπ Summary:")
print(f"- Total files: {len(file_list)}")
print(f"- Total chunks: {len(all_chunks)}")
print(f"- Total size: {total_size / 1024 / 1024:.2f} MB")
print(f"- Video size: {os.path.getsize(self.video_path) / 1024 / 1024:.2f} MB")
print(f"- Compression ratio: {os.path.getsize(self.video_path) / total_size * 100:.1f}%")
# Create zip package if requested
if create_zip:
print(f"\nπ¦ Creating shareable package...")
package_path = self.create_package(include_video_only=video_only_zip)
print(f"β
Package created: {package_path}")
print(f" Size: {os.path.getsize(package_path) / 1024 / 1024:.2f} MB")
print(f"\nπ‘ Next steps:")
print(f"1. Run interactive chat: python {os.path.basename(__file__)} chat")
print(f"2. Share the folder: {self.output_dir}")
if create_zip:
print(f"3. Or share the zip: {os.path.basename(package_path)}")
return True
# Query methods
def search_codebase(self, query: str, top_k: int = 5) -> str:
"""Search the codebase with enhanced contextual understanding."""
if not self.retriever:
if not self.video_exists():
return "Knowledge base not found. Run 'generate' first."
self.initialize_memvid()
# Enhance query for better results
enhanced_queries = self._enhance_search_query(query)
# Suppress all output during search including logging
import logging
old_level = logging.root.level
logging.root.setLevel(logging.CRITICAL)
all_results = []
try:
with io.StringIO() as buf, redirect_stdout(buf), redirect_stderr(buf):
# Search with enhanced queries
for enhanced_query in enhanced_queries:
results = self.retriever.search_with_metadata(enhanced_query, top_k=max(3, top_k//2))
for result in results: